Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

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.

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

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.

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'
});

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.

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

Just for fun, here is the way using function :

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

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

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

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

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'
});
JSON.parse(jsonString);

json.parse will change into object.

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 || {};
  }
};

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

JSON.parse(JSON.stringify(object))

If we have a string like this: "{\"status\":1,\"token\":\"65b4352b2dfc4957a09add0ce5714059\"}" then we can simply use JSON.parse twice to convert this string to a JSON object:

var sampleString = "{\"status\":1,\"token\":\"65b4352b2dfc4957a09add0ce5714059\"}"
var jsonString= JSON.parse(sampleString)
var jsonObject= JSON.parse(jsonString)

And simply we can extract values from JSON object using:

    // instead of last JSON.parse:
    var { status, token } = JSON.parse(jsonString);

The result will be:

status = 1 and token = 65b4352b2dfc4957a09add0ce5714059

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

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.

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

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.

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

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

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/

Try this.This one is written in typescript.

         export function safeJsonParse(str: string) {
               try {
                 return JSON.parse(str);
                   } catch (e) {
                 return str;
                 }
           }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top