Home Safely turning a JSON string into an object
Reply: 20

Safely turning a JSON string into an object

Matt Sheppard
Matt Sheppard Published in 2008-09-05 00:12:01Z

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.

Matt Sheppard
Matt Sheppard Reply to 2015-01-09 22:23:29Z

Is a pure JavaScript approach so long as you can require a reasonably modern browser.

See also https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Mark Biek
Mark Biek Reply to 2008-09-05 00:13:51Z

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', {
  requestHeaders: {Accept: 'application/json'},
  onSuccess: function(transport){
    var json = transport.responseText.evalJSON(true);

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

Liam Reply to 2017-06-26 15:23:52Z

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.

xdazz Reply to 2013-04-29 07:39:37Z

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.

hexacyanide Reply to 2015-07-16 23:38:26Z
  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.

Quentin Reply to 2017-04-24 15:50:32Z

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

teleclimber Reply to 2010-12-06 22:34:17Z

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

Dorian Reply to 2017-02-06 00:17:24Z

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'
Daniel Reply to 2014-10-30 04:02:48Z

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);
ewwink Reply to 2017-07-29 02:51:25Z

If you want this method can be used on this way.Here Data object which you want ex:Data='{result:true,count:1}'

try {
  eval('var obj=' + Data);
catch(e) {

This method really helps in Nodejs If you are working with serial port programing

lessisawesome Reply to 2015-09-29 07:16:07Z

Just for fun, here is the way using function :

 jsonObject = (new Function('return ' + jsonFormatData))()
Dorian Reply to 2015-02-18 13:38:07Z

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'
Bharath Kumaar
Bharath Kumaar Reply to 2015-04-22 09:40:23Z

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);
Jorgesys Reply to 2016-06-07 21:29:17Z

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:

Pushkar Kathuria
Pushkar Kathuria Reply to 2016-12-03 15:32:36Z

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 :-


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

Shekhar Tyagi
Shekhar Tyagi Reply to 2016-12-19 13:05:06Z

json.parse will change into object.

Tahsin Turkoz
Tahsin Turkoz Reply to 2017-04-08 08:58:38Z

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 || {};
Sebyddd Reply to 2017-12-28 18:16:34Z

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

Durgpal Singh
Durgpal Singh Reply to 2017-07-26 08:58:53Z

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

Salomon Zhang
Salomon Zhang Reply to 2017-12-20 01:47:45Z

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.


JSON.parse(text[, reviver])



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.


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

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.427188 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO