我想用JavaScript解析JSON字符串。响应类似于
var response = '{"result":true,"count":1}';
如何从中获取值结果和计数?
我想用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,它很简单:
var response = '{"result":true,"count":1}';
var obj = $.parseJSON(response);
alert(obj.result); //true
alert(obj.count); //1
您可以像在其他答案中一样使用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
正如许多其他人提到的,大多数浏览器都支持JSON.parse和JSON.stringify。
现在,我还想补充一点,如果您正在使用AngularJS(我强烈推荐),那么它还提供了您需要的功能:
var myJson = '{"result": true, "count": 1}';
var obj = angular.fromJson(myJson);//equivalent to JSON.parse(myJson)
var backToJson = angular.toJson(obj);//equivalent to JSON.stringify(obj)
我只是想添加关于AngularJS的内容,以提供另一种选择。注意,AngularJS并不正式支持InternetExplorer8(以及更旧版本),尽管根据经验,大多数功能似乎都很好。
如果您想将JSON 3用于较旧的浏览器,可以通过以下方式有条件地加载:
<script>
window.JSON ||
document.write('<script src="//cdnjs.cloudflare.com/ajax/libs/json3/3.2.4/json3.min.js"><\/scr'+'ipt>');
</script>
现在,无论客户端运行什么浏览器,都可以使用标准的window.JSON对象。