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

Use simple code represented in the following link on MSDN.

var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);

and reverse

var str = JSON.stringify(arr);
查看更多
不流泪的眼
3楼-- · 2018-12-31 00:22

Using JSON.parse is probably the best way. Here's an example live demo

var jsonRes = '{ "students" : [' +
          '{ "firstName":"Michel" , "lastName":"John" ,"age":18},' +
          '{ "firstName":"Richard" , "lastName":"Joe","age":20 },' +
          '{ "firstName":"James" , "lastName":"Henry","age":15 } ]}';
var studentObject = JSON.parse(jsonRes);
查看更多
与风俱净
4楼-- · 2018-12-31 00:22

Officially documented:

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

Syntax

JSON.parse(text[, reviver])

Parameters

text

The string to parse as JSON. See the JSON object for a description of JSON syntax.

reviver (optional)

If a function, this prescribes how the value originally produced by parsing is transformed, before being returned.

Return value

The Object corresponding to the given JSON text.

Exceptions

Throws a SyntaxError exception if the string to parse is not valid JSON.

查看更多
与君花间醉酒
5楼-- · 2018-12-31 00:23

Parse the json string with JSON.parse(), and the data becomes a JavaScript object.

JSON.parse(jsonString)

Here, JSON represents to process json dataset.

Example, Imagine we received this text from a web server:

'{ "name":"John", "age":30, "city":"New York"}'

To parse into json object :

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}'); 

Here obj is respective JSON object which look like following.

{ "name":"John", "age":30, "city":"New York"}

To fetch value used . operator EXample :

obj.name // John
obj.age //30

To transfer opposite, Convert a JavaScript object into a string with JSON.stringify().

查看更多
梦该遗忘
6楼-- · 2018-12-31 00:24

Older question, I know, however nobody notice this solution by using new Function(), an anonymous function that returns the data.


Just an example:

 var oData = 'test1:"This is my object",test2:"This is my object"';

 if( typeof oData !== 'object' )
  try {
   oData = (new Function('return {'+oData+'};'))();
  }
  catch(e) { oData=false; }

 if( typeof oData !== 'object' )
  { alert( 'Error in code' ); }
 else {
        alert( oData.test1 );
        alert( oData.test2 );
      }

This is a little more safe because it executes inside a function and do not compile in your code directly. So if there is a function declaration inside it, it will not be bound to the default window object.

I use this to 'compile' configuration settings of DOM elements (for example the data attribute) simple and fast.

查看更多
怪性笑人.
7楼-- · 2018-12-31 00:25

I found a "better" way:

In CoffeeScript:

try data = JSON.parse(jqxhr.responseText)
data ||= { message: 'Server error, please retry' }

In Javascript:

var data;

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

data || (data = {
  message: 'Server error, please retry'
});
查看更多
登录 后发表回答