Tuesday 31 December 2019

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


Answer



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


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...