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.
Use simple code represented in the following link on MSDN.
and reverse
Using JSON.parse is probably the best way. Here's an example live demo
Officially documented:
The
JSON.parse()
method parses a JSON string, constructing the JavaScript value or object described by the string. An optionalreviver
function can be provided to perform a transformation on the resulting object before it is returned.Syntax
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.
Parse the json string with JSON.parse(), and the data becomes a JavaScript object.
Here, JSON represents to process json dataset.
Example, Imagine we received this text from a web server:
To parse into json object :
Here obj is respective JSON object which look like following.
To fetch value used . operator EXample :
To transfer opposite, Convert a JavaScript object into a string with JSON.stringify().
Older question, I know, however nobody notice this solution by using
new Function()
, an anonymous function that returns the data.Just an example:
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.
I found a "better" way:
In CoffeeScript:
In Javascript: