Safely turning a JSON string into an object

Matt Sheppard Source

Given a string of JSON data, how can you safely turn that string into a JavaScript object?

Obviously you can do this unsafely with something like...

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

...but that leaves us vulnerable to the json string containing other code, which it seems very dangerous to simply eval.

javascriptjson

Answers

answered 10 years ago Mark Biek #1

I'm not sure about other ways to do it but here's how you do it in Prototype (JSON tutorial).

new Ajax.Request('/some_url', {
  method:'get',
  requestHeaders: {Accept: 'application/json'},
  onSuccess: function(transport){
    var json = transport.responseText.evalJSON(true);
  }
});

Calling evalJSON() with true as the argument sanitizes the incoming string.

answered 10 years ago John #2

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

Edit: 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 4 different ones for Javascript. I believe most people would consider json2.js their goto implementation.

answered 10 years ago Leanan #3

If you're using jQuery, you can also just do $.getJSON(url, function(data) { });

Then you can do things like data.key1.something, data.key1.something_else, etc.

answered 8 years ago Prahlad #4

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

The callback is passed the returned data, which will be a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method.

answered 8 years ago Alex V #5

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

answered 8 years ago teleclimber #6

I have successfully been using json_sans_eval for a while now. According to its author, it is more secure than json2.js.

answered 7 years ago Jonathan. #7

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

answered 5 years ago Cody #8

This seems to be the issue:

An input is received, via ajax websocket etc, and it is always gonna be in String format - but you need to know if it is JSON.parsable. Touble is, that if you always run it through a 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'
});

answered 5 years ago Ronald #9

Use simple code represented in the following link on MSDN.

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

and reverse

var str = JSON.stringify(arr);

answered 4 years ago GPrathap #10

Try using the method with this Data object. ex:Data='{result:true,count:1}'

try {
  eval('var obj=' + Data);
  console.log(obj.count);
}
catch(e) {
  console.log(e.message);
}

This method really helps in Nodejs when you are working with serial port programming

answered 4 years ago lessisawesome #11

Just for fun, here is the way using function :

 jsonObject = (new Function('return ' + jsonFormatData))()

answered 4 years ago Dorian #12

I found a "better" way:

In CoffeeScript:

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

In Javascript:

var data;

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

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

answered 3 years ago Bharath Kumaar #13

Using JSON.parse is probably the best way. Here's an example live demo

var jsonRes = '{ "students" : [' +
          '{ "firstName":"Michel" , "lastName":"John" ,"age":18},' +
          '{ "firstName":"Richard" , "lastName":"Joe","age":20 },' +
          '{ "firstName":"James" , "lastName":"Henry","age":15 } ]}';
var studentObject = JSON.parse(jsonRes);

answered 3 years ago Jorgesys #14

The easiest way using parse() method:

var response = '{"result":true,"count":1}';
var JsonObject= JSON.parse(response);

then you can get the values of the Json elements, for example:

var myResponseResult = JsonObject.result;
var myResponseCount = JsonObject.count;

Using jQuery as described in the documentation:

JSON.parse(jsonString);

answered 2 years ago Pushkar Kathuria #15

JSON.parse() converts any JSON String passed into the function, to a JSON Object.

For Better understanding press F12 to open Inspect Element of your browser and go to console to write following commands : -

var response = '{"result":true,"count":1}'; //sample json object(string form)
JSON.parse(response); //converts passed string to JSON Object.

Now run the command :-

console.log(JSON.parse(response));

you'll get output as Object {result: true, count: 1}.

In order to use that Object, you can assign it to the variable let's say obj :-

var obj = JSON.parse(response);

Now by using obj and dot(.) operator you can access properties of the JSON Object.

Try to run the command

console.log(obj.result);

answered 2 years ago Shekhar Tyagi #16

JSON.parse(jsonString);

json.parse will change into object.

answered 2 years ago Tahsin Turkoz #17

JSON parsing is always pain in ass. If the input is not as expected it throws an error and crashes what you are doing. You can use the following tiny function to safely parse your input. It always turns an object even if the input is not valid or is already an object which is better for most cases.

JSON.safeParse = function (input, def) {
  // Convert null to empty object
  if (!input) {
    return def || {};
  } else if (Object.prototype.toString.call(input) === '[object Object]') {
    return input;
  }
  try {
    return JSON.parse(input);
  } catch (e) {
    return def || {};
  }
};

answered 1 year ago Liuver Reynier Durán Pérez #18

Converting the object to JSON, and then parsing it, works for me, like:

JSON.parse(JSON.stringify(object))

answered 1 year ago Durgpal Singh #19

You also can use reviver function to filter.

var data = JSON.parse(jsonString, function reviver(key, value) {
   //your code here to filter
});

for more information read JSON.parse

answered 9 months ago Salomon Zhang #20

Officially documented:

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

Syntax

JSON.parse(text[, reviver])

Parameters

text

The string to parse as JSON. See the JSON object for a description of JSON syntax.

reviver (optional)

If a function, this prescribes how the value originally produced by parsing is transformed, before being returned.

Return value

The Object corresponding to the given JSON text.

Exceptions

Throws a SyntaxError exception if the string to parse is not valid JSON.

answered 7 months ago Codebeat #21

Older question, I know, however nobody notice this solution by using new Function(), an anonymous function that returns the data.


Just an example:

 var oData = 'test1:"This is my object",test2:"This is my object"';

 if( typeof oData !== 'object' )
  try {
   oData = (new Function('return {'+oData+'};'))();
  }
  catch(e) { oData=false; }

 if( typeof oData !== 'object' )
  { alert( 'Error in code' ); }
 else {
        alert( oData.test1 );
        alert( oData.test2 );
      }

This is a little more safe because it executes inside a function and do not compile in your code directly. So if there is a function declaration inside it, it will not be bound to the default window object.

I use this to 'compile' configuration settings of DOM elements (for example the data attribute) simple and fast.

answered 4 months ago Chetabahana #22

If your JavaScript are in Mootools the JSON.parse will be Anonymous by the Framework.
A valid syntax to safely turning a JSON string into an object shall be:

var object = JSON.decode(string[, secure]);

Moreover a JSON Request is can raise an object that able to parse directly.
You may cek how it turn a json raw data here:

http://jsfiddle.net/chetabahana/qbx9b5pm/

answered 4 months ago Supun Dharmarathne #23

Try this.This one is written in typescript.

         export function safeJsonParse(str: string) {
               try {
                 return JSON.parse(str);
                   } catch (e) {
                 return str;
                 }
           }

answered 1 month ago FullStack #24

Parse the json string with JSON.parse(), and the data becomes a JavaScript object.

JSON.parse(jsonString)

Here, JSON represents to process json dataset.

Example, Imagine we received this text from a web server:

'{ "name":"John", "age":30, "city":"New York"}'

To parse into json object :

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}'); 

Here obj is respective JSON object which look like following.

{ "name":"John", "age":30, "city":"New York"}

To fetch value used . operator EXample :

obj.name // John
obj.age //30

To transfer opposite, Convert a JavaScript object into a string with JSON.stringify().

answered 1 month ago Willem van der Veen #25

Summary:

Javascript (both browser and NodeJS) have a built in JSON object. On this Object are 2 convenient methods for dealing with JSON. They are the following:

  1. JSON.parse() Takes JSON as argument, returns JS object
  2. JSON.stringify() Takes JS object as argument returns JSON object

Other applications:

Besides for very conveniently dealing with JSON they have can be used for other means. The combination of both JSON methods allows us to make very easy make deep clones of arrays or objects. For example:

let arr1 = [1, 2, [3 ,4]];
let newArr = arr1.slice();

arr1[2][0] = 'changed'; 
console.log(newArr); // not a deep clone

let arr2 = [1, 2, [3 ,4]];
let newArrDeepclone = JSON.parse(JSON.stringify(arr2));

arr2[2][0] = 'changed'; 
console.log(newArrDeepclone); // A deep clone, values unchanged

comments powered by Disqus