Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 987
Matt Sheppard Avatar asked Sep 05 '08 00:09

Matt Sheppard


People also ask

How can I convert JSON to object?

Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON.

How do you convert a string to a JSON object in Python?

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.


2 Answers

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

like image 71
Jonathan. Avatar answered Sep 20 '22 10:09

Jonathan.


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

like image 35
Alex V Avatar answered Sep 19 '22 10:09

Alex V