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:01

If you're using jQuery, you can also just do $.getJSON(url, function(data) { });

Then you can do things like data.key1.something, data.key1.something_else, etc.

查看更多
情到深处是孤独
3楼-- · 2018-12-31 00:03

The easiest way using parse() method:

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

then you can get the values of the Json elements, for example:

var myResponseResult = JsonObject.result;
var myResponseCount = JsonObject.count;

Using jQuery as described in the documentation:

JSON.parse(jsonString);
查看更多
ら面具成の殇う
4楼-- · 2018-12-31 00:07

This seems to be the issue:

An input is received, via ajax websocket etc, and it is always gonna be in String format - but you need to know if it is JSON.parsable. Touble is, that if you always run it through a JSON.parse, the program MAY continue 'successfully' but you'll still see an error thrown in the console with the dreaded "Error: unexpected token 'x'".

var data;

try {
  data = JSON.parse(jqxhr.responseText);
} catch (_error) {}

data || (data = {
  message: 'Server error, please retry'
});
查看更多
查无此人
5楼-- · 2018-12-31 00:09

Converting the object to JSON, and then parsing it, works for me, like:

JSON.parse(JSON.stringify(object))
查看更多
看风景的人
6楼-- · 2018-12-31 00:09

Summary:

Javascript (both browser and NodeJS) have a built in JSON object. On this Object are 2 convenient methods for dealing with JSON. They are the following:

  1. JSON.parse() Takes JSON as argument, returns JS object
  2. JSON.stringify() Takes JS object as argument returns JSON object

Other applications:

Besides for very conveniently dealing with JSON they have can be used for other means. The combination of both JSON methods allows us to make very easy make deep clones of arrays or objects. For example:

let arr1 = [1, 2, [3 ,4]];
let newArr = arr1.slice();

arr1[2][0] = 'changed'; 
console.log(newArr); // not a deep clone

let arr2 = [1, 2, [3 ,4]];
let newArrDeepclone = JSON.parse(JSON.stringify(arr2));

arr2[2][0] = 'changed'; 
console.log(newArrDeepclone); // A deep clone, values unchanged

查看更多
妖精总统
7楼-- · 2018-12-31 00:10
$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

The callback is passed the returned data, which will be a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method.

查看更多
登录 后发表回答