Safely turning a JSON string into an object

2018-12-30 23:56发布

Given a string of JSON data, how can you safely turn that string into a JavaScript object?

Obviously you can do this unsafely with something like...

var obj = eval("(" + json + ')');

...but that leaves us vulnerable to the json string containing other code, which it seems very dangerous to simply eval.

24条回答
一个人的天荒地老
2楼-- · 2018-12-31 00:12
JSON.parse(jsonString);

json.parse will change into object.

查看更多
弹指情弦暗扣
3楼-- · 2018-12-31 00:13

You also can use reviver function to filter.

var data = JSON.parse(jsonString, function reviver(key, value) {
   //your code here to filter
});

for more information read JSON.parse

查看更多
裙下三千臣
4楼-- · 2018-12-31 00:14

Just for fun, here is the way using function :

 jsonObject = (new Function('return ' + jsonFormatData))()
查看更多
孤独寂梦人
5楼-- · 2018-12-31 00:14

JSON.parse() converts any JSON String passed into the function, to a JSON Object.

For Better understanding press F12 to open Inspect Element of your browser and go to console to write following commands : -

var response = '{"result":true,"count":1}'; //sample json object(string form)
JSON.parse(response); //converts passed string to JSON Object.

Now run the command :-

console.log(JSON.parse(response));

you'll get output as Object {result: true, count: 1}.

In order to use that Object, you can assign it to the variable let's say obj :-

var obj = JSON.parse(response);

Now by using obj and dot(.) operator you can access properties of the JSON Object.

Try to run the command

console.log(obj.result);
查看更多
倾城一夜雪
6楼-- · 2018-12-31 00:17

The jQuery method is now deprecated. Use this method instead:

let jsonObject = JSON.parse(jsonString);

Original answer using deprecated jQuery functionality:

If you're using jQuery just use:

jQuery.parseJSON( jsonString );

It's exactly what you're looking for (see the jQuery documentation).

查看更多
只靠听说
7楼-- · 2018-12-31 00:17

Edit: This answer is for IE < 7, for modern browsers check Jonathan's answer above.

Edit: This answer is outdated and Jonathan's answer above (JSON.parse(jsonString)) is now the best answer.

JSON.org has JSON parsers for many languages including 4 different ones for Javascript. I believe most people would consider json2.js their goto implementation.

查看更多
登录 后发表回答