Safely turning a JSON string into an object

ghz 1years ago ⋅ 5032 views

Question

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

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