Coder Perfect

Converting a JSON string to an object in a secure manner

Problem

How can I convert a string of JSON data into a JavaScript object in a secure manner?

Obviously, I can accomplish this in a dangerous manner using something like:

var obj = eval("(" + json + ')');

However, this exposes me to the JSON string containing additional code, which appears to be quite dangerous to simply eval.

Asked by Matt Sheppard

Solution #1

If you can ensure a decently contemporary browser, JSON.parse(jsonString) is a pure JavaScript technique.

Answered by Jonathan.

Solution #2

The jQuery approach is no longer supported. Instead, try this method:

let jsonObject = JSON.parse(jsonString);

Original response, which made use of deprecated jQuery functionality:

Simply use: if you’re using jQuery.

jQuery.parseJSON( jsonString );

It’s just what you’ve been looking for (see the jQuery documentation).

Answered by Alex V

Solution #3

This response is for Internet Explorer 7; for contemporary browsers, see Jonathan’s response above.

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

JSON.org contains parsers for a variety of languages, including four different JavaScript parsers. Most people, I believe, would use json2.js as their go-to implementation.

Answered by John

Solution #4

Use the following code from “JSON.parse()” as an example:

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

and reversing it:

var str = JSON.stringify(arr);

Answered by Ronald Coarite

Solution #5

This seems to be the issue:

The input will be in String format and received over Ajax websocket, but you need to know if it is JSON.parsable. The problem is that if you constantly run it through JSON.parse, the program may continue “successfully,” but you’ll still get the dreaded “Error: unexpected token ‘x'” error in the console.

var data;

try {
  data = JSON.parse(jqxhr.responseText);
} catch (_error) {}

data || (data = {
  message: 'Server error, please retry'
});

Answered by Cody

Post is based on https://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object