我想用JavaScript解析JSON字符串。响应类似于

var response = '{"result":true,"count":1}';

如何从中获取值结果和计数?


当前回答

如果使用DojoToolkit:

require(["dojo/json"], function(JSON){
    JSON.parse('{"hello":"world"}', true);
});

其他回答

我认为JSON.parse(myObject)可以工作。但根据浏览器的不同,它可能值得使用eval('('+myObject+')')。我唯一建议注意的问题是JSON中的多级列表。

如果使用jQuery,它很简单:

var response = '{"result":true,"count":1}';
var obj = $.parseJSON(response);
alert(obj.result); //true
alert(obj.count); //1

一种简单的方法:

var data = '{"result":true,"count":1}';
var json = eval("[" +data+ "]")[0]; // ;)

如果使用DojoToolkit:

require(["dojo/json"], function(JSON){
    JSON.parse('{"hello":"world"}', true);
});

JSON.parse()将传递给函数的任何JSON字符串转换为JSON对象。

为了更好地理解,请按F12打开浏览器的Inspect Element,然后转到控制台编写以下命令:

var response = '{"result":true,"count":1}'; // Sample JSON object (string form)
JSON.parse(response); // Converts passed string to a JSON object.

现在运行命令:

console.log(JSON.parse(response));

您将得到对象{result:true,count:1}的输出。

为了使用该对象,可以将其分配给变量,例如obj:

var obj = JSON.parse(response);

现在,通过使用obj和dot(.)操作符,您可以访问JSON对象的财产。

尝试运行命令

console.log(obj.result);