【问题标题】:Convert JSON string from fetch to object将 JSON 字符串从 fetch 转换为 object
【发布时间】:2017-09-16 16:24:36
【问题描述】:

我需要将我的 JSON 响应转换为对象,我该如何实现?

我的 JSON 响应:

[  
   {  
      "id":296,
      "nama":"Appetizer"
   },
   {  
      "id":295,
      "nama":"Bahan"
   }
]

【问题讨论】:

    标签: json fetch-api


    【解决方案1】:

    如果您的响应是有效的 JSON,就这样做

    var obj = JSON.parse(response);
    

    【讨论】:

      【解决方案2】:

      如果 JSON 无效,您需要在 try catch 中使用 JSON.parse 来捕获错误。

      let str = '[{"id":296,"nama":"Appetizer"},{"id":295,"nama":"Bahan"}]';
      
      try {
        let obj = JSON.parse(str);
      } catch (ex) {
        console.error(ex);
      }
      

      要将您的对象转换回字符串,请使用 Stringify

      JSON.stringify(obj)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-14
        • 2020-12-26
        • 1970-01-01
        • 2020-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-18
        相关资源
        最近更新 更多