【发布时间】:2017-09-16 16:24:36
【问题描述】:
我需要将我的 JSON 响应转换为对象,我该如何实现?
我的 JSON 响应:
[
{
"id":296,
"nama":"Appetizer"
},
{
"id":295,
"nama":"Bahan"
}
]
【问题讨论】:
我需要将我的 JSON 响应转换为对象,我该如何实现?
我的 JSON 响应:
[
{
"id":296,
"nama":"Appetizer"
},
{
"id":295,
"nama":"Bahan"
}
]
【问题讨论】:
如果您的响应是有效的 JSON,就这样做
var obj = JSON.parse(response);
【讨论】:
如果 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)
【讨论】: