Home Parse JSON in JavaScript?
Reply: 16

Parse JSON in JavaScript?

Peter Mortensen
1#
Peter Mortensen Published in 2011-02-08 16:34:03Z

This question already has an answer here:

  • Safely turning a JSON string into an object 21 answers

I want to parse a JSON string in JavaScript. The response is something like

var response = '{"result":true,"count":1}';

How can I get the values result and count from this?

Peter Mortensen
2#
Peter Mortensen Reply to 2017-05-25 21:09:08Z

Most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JavaScript is based on). Its usage is simple:

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

alert(obj.count);

For the browsers that don't you can implement it using json2.js.

As noted in the comments, if you're already using jQuery, there is a $.parseJSON function that maps to JSON.parse if available or a form of eval in older browsers. However, this performs additional, unnecessary checks that are also performed by JSON.parse, so for the best all round performance I'd recommend using it like so:

var json = '{"result":true,"count":1}',
    obj = JSON && JSON.parse(json) || $.parseJSON(json);

This will ensure you use native JSON.parse immediately, rather than having jQuery perform sanity checks on the string before passing it to the native parsing function.

El Ronnoco
3#
El Ronnoco Reply to 2011-02-08 16:45:37Z

Without using a library you can use eval - the only time you should use. It's safer to use a library though.

eg...

var response = '{"result":true , "count":1}';

var parsedJSON = eval('('+response+')');

var result=parsedJSON.result;
var count=parsedJSON.count;

alert('result:'+result+' count:'+count);
mukesh krishnan
4#
mukesh krishnan Reply to 2017-02-28 11:17:39Z

First of all, you have to make sure that the JSON code is valid.

After that, I would recommend using a JavaScript library such as jQuery or Prototype if you can because these things are handled well in those libraries.

On the other hand, if you don't want to use a library and you can vouch for the validity of the JSON object, I would simply wrap the string in an anonymous function and use the eval function.

This is not recommended if you are getting the JSON object from another source that isn't absolutely trusted because the eval function allows for renegade code if you will.

Here is an example of using the eval function:

var strJSON = '{"result":true,"count":1}';
var objJSON = eval("(function(){return " + strJSON + ";})()");
alert(objJSON.result);
alert(objJSON.count);

If you control what browser is being used or you are not worried people with an older browser, you can always use the JSON.parse method.

This is really the ideal solution for the future.

milestyle
5#
milestyle Reply to 2012-07-18 21:57:41Z

If you are getting this from an outside site it might be helpful to use jquery's getJSON. If it's a list you can iterate through it with $.each

$.getJSON(url, function (json) {
    alert(json.result);
    $.each(json.list, function (i, fb) {
        alert(fb.result);
    });
});
ha9u63ar
6#
ha9u63ar Reply to 2013-04-04 10:38:37Z

I thought JSON.parse(myObject) would work. But depending on the browsers, it might be worth using eval('('+myObject+')'). The only issue I can recommend watching out for is the multi-level list in JSON.

Peter Mortensen
7#
Peter Mortensen Reply to 2014-06-06 13:58:16Z

If you want to use JSON 3 for older browsers, you can load it conditionally with:

<script>
    window.JSON || 
    document.write('<script src="//cdnjs.cloudflare.com/ajax/libs/json3/3.2.4/json3.min.js"><\/scr'+'ipt>');
</script>

Now the standard window.JSON object is available to you no matter what browser a client is running.

Peter Mortensen
8#
Peter Mortensen Reply to 2014-06-06 13:59:43Z

You can either use the eval function as in some other answers. (Don't forget the extra braces.) You will know why when you dig deeper), or simply use the jQuery function parseJSON:

var response = '{"result":true , "count":1}'; 
var parsedJSON = $.parseJSON(response);

OR

You can use this below code.

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

And you can access the fields using jsonObject.result and jsonObject.count.

Peter Mortensen
9#
Peter Mortensen Reply to 2014-06-06 14:00:53Z

The following example will make it clear:

var jsontext   = '{"name":"x","age":"11"}';
var getContact = JSON.parse(jsontext);
document.write(getContact.name + ", " + getContact.age);

// Output: x, 11

OR

You can also use the eval function. The following example is using the eval function:

var jsontext   = '{"name":"x","age":"11"}';
var getContact = eval('(' + jsontext + ')');
document.write(getContact.name + ", " + getContact.age);

// Output: x, 11

Since the JSON.parse function is more secure and executes faster than the eval function, I recommend you to use JSON.parse function.

Peter Mortensen
10#
Peter Mortensen Reply to 2014-06-06 14:01:18Z

If you use jQuery, it is simple:

var response = '{"result":true,"count":1}';
var obj = $.parseJSON(response);
alert(obj.result); //true
alert(obj.count); //1
Peter Mortensen
11#
Peter Mortensen Reply to 2017-05-25 21:14:40Z

As mentioned by numerous others, most browsers support JSON.parse and JSON.stringify.

Now, I'd also like to add that if you are using AngularJS (which I highly recommend), then it also provides the functionality that you require:

var myJson = '{"result": true, "count": 1}';
var obj = angular.fromJson(myJson);//equivalent to JSON.parse(myJson)
var backToJson = angular.toJson(obj);//equivalent to JSON.stringify(obj)

I just wanted to add the stuff about AngularJS to provide another option. NOTE that AngularJS doesn't officially support Internet Explorer 8 (and older versions, for that matter), though through experience most of the stuff seems to work pretty well.

Peter Mortensen
12#
Peter Mortensen Reply to 2017-05-25 21:13:49Z

If you use Dojo Toolkit:

require(["dojo/json"], function(JSON){
    JSON.parse('{"hello":"world"}', true);
});
Peter Mortensen
13#
Peter Mortensen Reply to 2017-05-25 21:13:11Z

An easy way to do it:

var data = '{"result":true,"count":1}';
var json = eval("[" +data+ "]")[0]; // ;)
Peter Mortensen
14#
Peter Mortensen Reply to 2017-05-25 21:12:57Z

If you pass a string variable (a well-formed JSON string) to JSON.parse from MVC @Viewbag that has doublequote, '"', as quotes, you need to process it before JSON.parse (jsonstring)

    var jsonstring = '@ViewBag.jsonstring';
    jsonstring = jsonstring.replace(/&quot;/g, '"');  
Peter Mortensen
15#
Peter Mortensen Reply to 2017-05-25 21:11:55Z

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

For better understanding, press F12 to open the Inspect Element of your browser, and go to the console to write the following commands:

var response = '{"result":true,"count":1}'; // Sample JSON object (string form)
JSON.parse(response); // Converts passed string to a 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 the dot(.) operator you can access properties of the JSON Object.

Try to run the command

console.log(obj.result);
Peter Mortensen
16#
Peter Mortensen Reply to 2017-05-25 21:10:07Z

If you like

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

you can access the JSON elements by JsonObject with (.) dot:

JsonObject.result;
JsonObject.count;
Jorgesys
17#
Jorgesys Reply to 2016-02-20 00:58:42Z

The easiest way using parse() method:

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

this is an example of how to get values:

var myResponseResult = JsonObject.a;
var myResponseCount = JsonObject.b;
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO