Safely turning a JSON string into an object

Matt Sheppard picture Matt Sheppard · Sep 5, 2008 · Viewed 1.3M times · Source

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.

Answer

Jonathan. picture Jonathan. · Apr 16, 2011

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