Safely turning a JSON string into an object

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

Obviously I can do this unsafely with something like:

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

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


Solution 1:

JSON.parse(jsonString) is a pure JavaScript approach so long as you can guarantee a reasonably modern browser.

Solution 2:

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).

Solution 3:

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

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 four different ones for JavaScript. I believe most people would consider json2.js their goto implementation.

Solution 4:

Use the simple code example in "JSON.parse()":

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

and reversing it:

var str = JSON.stringify(arr);