将 JSON 字符串从 fetch 转换为对象
Convert JSON string from fetch to object
我需要将我的 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)
我需要将我的 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)