我想用JavaScript解析JSON字符串。响应类似于
var response = '{"result":true,"count":1}';
如何从中获取值结果和计数?
我想用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
其他回答
如果使用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]; // ;)
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);
以下示例将明确说明:
let contactJSON = '{"name":"John Doe","age":"11"}';
let contact = JSON.parse(contactJSON);
console.log(contact.name + ", " + contact.age);
// Output: John Doe, 11
使用parse()方法的最简单方法:
var response = '{"a":true,"b":1}';
var JsonObject= JSON.parse(response);
这是如何获取值的示例:
var myResponseResult = JsonObject.a;
var myResponseCount = JsonObject.b;