Safely turning a JSON string into an object – Dev

The best answers to the question “Safely turning a JSON string into an object” in the category Dev.


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.


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


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


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


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