Parse JSON in JavaScript? [duplicate]

2020-01-22 11:03发布

I want to parse a JSON string in JavaScript. The response is something like

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

How can I get the values result and count from this?

16条回答
太酷不给撩
2楼-- · 2020-01-22 11:17

If you use jQuery, it is simple:

var response = '{"result":true,"count":1}';
var obj = $.parseJSON(response);
alert(obj.result); //true
alert(obj.count); //1
查看更多
做自己的国王
3楼-- · 2020-01-22 11:18

WARNING!

This answer stems from an ancient era of JavaScript programming during which there was no builtin way to parse JSON. The advice given here is no longer applicable and probably dangerous. From a modern perspective, parsing JSON by involving jQuery or calling eval() is nonsense. Unless you need to support IE 7 or Firefox 3.0, the correct way to parse JSON is JSON.parse().

First of all, you have to make sure that the JSON code is valid.

After that, I would recommend using a JavaScript library such as jQuery or Prototype if you can because these things are handled well in those libraries.

On the other hand, if you don't want to use a library and you can vouch for the validity of the JSON object, I would simply wrap the string in an anonymous function and use the eval function.

This is not recommended if you are getting the JSON object from another source that isn't absolutely trusted because the eval function allows for renegade code if you will.

Here is an example of using the eval function:

var strJSON = '{"result":true,"count":1}';
var objJSON = eval("(function(){return " + strJSON + ";})()");
alert(objJSON.result);
alert(objJSON.count);

If you control what browser is being used or you are not worried people with an older browser, you can always use the JSON.parse method.

This is really the ideal solution for the future.

查看更多
家丑人穷心不美
4楼-- · 2020-01-22 11:18

The following example will make it clear:

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

// Output: John Doe, 11
查看更多
甜甜的少女心
5楼-- · 2020-01-22 11:20

If you like

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

you can access the JSON elements by JsonObject with (.) dot:

JsonObject.result;
JsonObject.count;
查看更多
Bombasti
6楼-- · 2020-01-22 11:20

If you use Dojo Toolkit:

require(["dojo/json"], function(JSON){
    JSON.parse('{"hello":"world"}', true);
});
查看更多
走好不送
7楼-- · 2020-01-22 11:22

You can either use the eval function as in some other answers. (Don't forget the extra braces.) You will know why when you dig deeper), or simply use the jQuery function parseJSON:

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

OR

You can use this below code.

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

And you can access the fields using jsonObject.result and jsonObject.count.

查看更多
登录 后发表回答