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?

upvote
  flag
var json = '{"result":true,"count":1}', obj = JSON.parse(json); console.log(obj.count); // if use in nodejs then use console – Shekhar Tyagi

16 Answers 11

up vote 1823 down vote accepted

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.

upvote
  flag
i think JSON.parse not working in IE ?? – Marwan
28 upvote
  flag
@Marwan: IE 8+ supports JSON.parse(). For IE 6, 7 and other older browsers, you can use the json2.js I linked to from my post. Alternatively, but less securely, you can use eval. – Andy E
upvote
  flag
@AndyE, you can also use jQuery too (in case it already included jQuery, he doesn't need an extra library.) – Derek 朕會功夫
9 upvote
  flag
Unless he also needs JSON.stringify() – ThiefMaster
14 upvote
  flag
Note to reviewers: please thoroughly check peer edits before allowing them, as your actions may cause unwanted side-effects for users copying and pasting code from answers. – Andy E
upvote
  flag
Shouldn't you just stick with $.parseJSON? – chaz
1 upvote
  flag
If you implement the JSON3 library this will fill in the gaps in browsers that do not natively support JavaScript, such as IE7 – Liam
12 upvote
  flag
It's not necessary to check for native support first and then fall back to jQuery. jQuery 1.10 tries JSON.parse first, then the own implementation. jQuery 2.x is directly calling JSON.parse without checking or fallback. – Jasha
4 upvote
  flag
Browser support details: Can I use JSON parsing – Peter V. Mørch
upvote
  flag
eval() will also parse json to javascript objects. But eval() function can compile and execute any javascripts too. So, if uses eval(), there is a potential security issue. – Janaka R Rajapaksha
2 upvote
  flag
@AndyE, what if the JSON is '{"1":{"result":"true","count":"1"},"2":{"result":"false","c‌​ount":"2"}}' instead ? We'll have a [Object object] in output. How to do it in this case ? – hacks4life
upvote
  flag
Since this post is one of the most popular ones on JSON in SO, can someone please include a thorough guideline to give an understanding on JSON escape characters as well? – Barry Guvenkaya
upvote
  flag
I'm going to be that guy who posts on a 5-year-old answer...If you execute obj = JSON && JSON.parse(json) || $.parseJSON(json), and the json string represents a falsy value, like 0 or null, then both JSON.parse and $.parseJSON will fire, because the JSON && JSON.parse(json) part evaluates to a falsy value. So it's technically not quite the best all around performance, but it would of course be a negligible difference. – Joe Enos

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);
upvote
  flag
eval cant handle a json string which return as HTML – user192344
12 upvote
  flag
IF it's html-encoded it's not JSON anymore. – ThiefMaster
2 upvote
  flag
eval expects valid javascript, which JSON might not be, so eval cannot parse some valid JSON texts (for example, U+2028 is valid in JSON, not valid in javascript). – Marc Lehmann

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.

upvote
  flag
Great man! I couldn't import the JSON lib, because it conflicted with other libs – Tahir Malik
19 upvote
  flag
eval() is OK to fulfill a job, while it may compile and execute any Javascript program, so there can be security issues. I think JSON.parse() is a better choice. – ray6080
4 upvote
  flag
Note for passerby: here's a good online tool to check if your JSON string is valid: jsonlint.com – Amal Murali
10 upvote
  flag
NO, NO, NO!!! Using eval to evaluate JSON is a really dangerous idea. Are you 100% certain there is no possibility that someone could inject their own code into your string? – Charles
2 upvote
  flag
Worth mentioning that there's no such a thing as a JSON object. – Jezen Thomas

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

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.

2 upvote
  flag
eval() can compile and execute any javascript too. so you are at a potential security issue if using eval(). but json parser will recognize only json strings and compile them into javascript objects. – Janaka R Rajapaksha

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.

1 upvote
  flag
It is available to you after json3.min.js has finished loading. This doesn't give you a callback when it is available. So your code may work today, but won't work on wednesday when cdnjs.cloudflare.com is suddenly slower than usual or the network is loaded or one of 10000 other reasons. RequireJS instead. – Peter V. Mørch
5 upvote
  flag
Peter, that is not correct. Both the loading of external scripts and document.write are synchronous activities, so all scripts placed after will wait until it's loaded before executing. For loading just JSON3, this is a fine approach. RequireJS would come in handy if your project grew in complexity and had to load scripts with complex dependency relationships. Just remember that document.write will block page rendering, so place it at the bottom of your markup. – huwiler
2 upvote
  flag
Sorry; I think you're right. Please disregard my comment as bogus. – Peter V. Mørch
upvote
  flag
Peter, your 1st comment is informative & useful (good to have that warning), just not applicable in 100% of cases. For a slightly more stable & faster CDN, you can use jsDelivr: //cdn.jsdelivr.net/json3/latest/json3.min.js – tomByrer

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.

upvote
  flag
jsonObject.count in the console.log returns undefined. How should I call it? – Sahar Ch.

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.

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
2 upvote
  flag
The same answer is already presented on this question. //allinonescript.com/a/16953423/2392330 – idlerboris
upvote
  flag
sorry, I have not seen that above. – legendJSLC

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.

If you use Dojo Toolkit:

require(["dojo/json"], function(JSON){
    JSON.parse('{"hello":"world"}', true);
});
upvote
  flag
var j='[{ "name":"John", "age":30, "city":"New York"}, { "name":"George", "age":48, "city":"Kutaisi"}]'; var obj = JSON.parse(j); alert(obj.length); for(var i=0; i<obj.length; i++){ alert(obj[i].city + ' ' + obj[i].age); } – GGSoft

An easy way to do it:

var data = '{"result":true,"count":1}';
var json = eval("[" +data+ "]")[0]; // ;)

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, '"');  
upvote
  flag
What do you mean with that? Why do you post an answer for an ancient question? – kay
5 upvote
  flag
What they said in the previous answers do not help the case that if the parameter value has double quotes in the string. It needs to be replaced globally with a real double quote !! I find out in a hard way just to share in case somebody has the same problem – Jenna Leaf
4 upvote
  flag
Kay: I clarified my posting right now, this is the first time I've ever tried to help. Please look at the posting again. You know that quote thing output from server page is a real problem to JSON.parse(). – Jenna Leaf

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

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;

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;

Not the answer you're looking for? Browse other questions tagged or ask your own question.