我想用JavaScript解析JSON字符串。响应类似于
var response = '{"result":true,"count":1}';
如何从中获取值结果和计数?
我想用JavaScript解析JSON字符串。响应类似于
var response = '{"result":true,"count":1}';
如何从中获取值结果和计数?
当前回答
在不使用库的情况下,您可以使用eval,这是您应该使用的唯一时间。不过使用图书馆更安全。
如。。。
var response = '{"result":true , "count":1}';
var parsedJSON = eval('('+response+')');
var result=parsedJSON.result;
var count=parsedJSON.count;
alert('result:'+result+' count:'+count);
其他回答
我认为JSON.parse(myObject)可以工作。但根据浏览器的不同,它可能值得使用eval('('+myObject+')')。我唯一建议注意的问题是JSON中的多级列表。
如果使用DojoToolkit:
require(["dojo/json"], function(JSON){
JSON.parse('{"hello":"world"}', true);
});
在不使用库的情况下,您可以使用eval,这是您应该使用的唯一时间。不过使用图书馆更安全。
如。。。
var response = '{"result":true , "count":1}';
var parsedJSON = eval('('+response+')');
var result=parsedJSON.result;
var count=parsedJSON.count;
alert('result:'+result+' count:'+count);
使用parse()方法的最简单方法:
var response = '{"a":true,"b":1}';
var JsonObject= JSON.parse(response);
这是如何获取值的示例:
var myResponseResult = JsonObject.a;
var myResponseCount = JsonObject.b;
以下示例将明确说明:
let contactJSON = '{"name":"John Doe","age":"11"}';
let contact = JSON.parse(contactJSON);
console.log(contact.name + ", " + contact.age);
// Output: John Doe, 11