Javascript – Safely turning a JSON string into an object

javascriptjsonparsing

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.

Best Solution

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