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

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

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


当前回答

如果使用DojoToolkit:

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

其他回答

以下示例将明确说明:

let contactJSON = '{"name":"John Doe","age":"11"}';
let contact = JSON.parse(contactJSON);
console.log(contact.name + ", " + contact.age);

// Output: John Doe, 11

如果您是从外部站点获取此信息,那么使用jQuery的getJSON可能会有所帮助。如果它是一个列表,你可以用$.each遍历它

$.getJSON(url, function (json) {
    alert(json.result);
    $.each(json.list, function (i, fb) {
        alert(fb.result);
    });
});

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);

如果从MVC@Viewbag向JSON.parse传递一个字符串变量(格式良好的JSON字符串),该变量包含双引号“”作为引号,则需要在JSON.pase(jsonsring)之前处理它

    var jsonstring = '@ViewBag.jsonstring';
    jsonstring = jsonstring.replace(/"/g, '"');  

在不使用库的情况下,您可以使用eval,这是您应该使用的唯一时间。不过使用图书馆更安全。

如。。。

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

var parsedJSON = eval('('+response+')');

var result=parsedJSON.result;
var count=parsedJSON.count;

alert('result:'+result+' count:'+count);