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

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

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


当前回答

如果使用jQuery,它很简单:

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

其他回答

使用parse()方法的最简单方法:

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

这是如何获取值的示例:

var myResponseResult = JsonObject.a;
var myResponseCount = JsonObject.b;

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

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

您可以像在其他答案中一样使用eval函数。(不要忘记额外的大括号。)当你深入研究时,你会知道为什么),或者简单地使用jQuery函数parseJSON:

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

OR

您可以使用以下代码。

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

您可以使用jsonObject.result和jsonObject.count访问这些字段。

更新:

如果输出未定义,则需要遵循此答案。也许您的json字符串具有数组格式。您需要像这样访问json对象财产

var response = '[{"result":true , "count":1}]'; // <~ Array with [] tag
var jsonObject = JSON.parse(response);
console.log(jsonObject[0].result); //Output true
console.log(jsonObject[0].count); //Output 1

如果使用jQuery,它很简单:

var response = '{"result":true,"count":1}';
var obj = $.parseJSON(response);
alert(obj.result); //true
alert(obj.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);