javascript - Safely turning a JSON string into an object

ID : 811

viewed : 173

Tags : javascriptjsonparsingjavascript





Top 5 Answer for javascript - Safely turning a JSON string into an object

vote vote

98

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

vote vote

83

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

vote vote

77

This answer is for IE < 7, for modern browsers check Jonathan's answer above.

This answer is outdated and Jonathan's answer above (JSON.parse(jsonString)) is now the best answer.

JSON.org has JSON parsers for many languages including four different ones for JavaScript. I believe most people would consider json2.js their goto implementation.

vote vote

62

Use the simple code example in "JSON.parse()":

var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}'; var contact = JSON.parse(jsontext); 

and reversing it:

var str = JSON.stringify(arr); 
vote vote

53

This seems to be the issue:

An input that is received via Ajax websocket etc, and it will be in String format, but you need to know if it is JSON.parsable. The touble is, if you always run it through JSON.parse, the program MAY continue "successfully" but you'll still see an error thrown in the console with the dreaded "Error: unexpected token 'x'".

var data;  try {   data = JSON.parse(jqxhr.responseText); } catch (_error) {}  data || (data = {   message: 'Server error, please retry' }); 

Top 3 video Explaining javascript - Safely turning a JSON string into an object







Related QUESTION?