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

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

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


当前回答

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

其他回答

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

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

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

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

如果你愿意

var response = '{"result":true,"count":1}';
var JsonObject= JSON.parse(response);

您可以通过JsonObject使用(.)dot访问JSON元素:

JsonObject.result;
JsonObject.count;

如果使用jQuery,它很简单:

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

以下示例将明确说明:

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

// Output: John Doe, 11