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.
Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON.
Use the json. you can turn it into JSON in Python using the json. loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary.
JSON.parse(jsonString)
is a pure JavaScript approach so long as you can guarantee a reasonably modern browser.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With