Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
possible duplicate of Serializing to JSON in jQuery –  outis Dec 26 '11 at 10:10
add comment

9 Answers

up vote 756 down vote accepted

Most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS 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.

share|improve this answer
14  
@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 Nov 16 '11 at 9:46
3  
Unless he also needs JSON.stringify() –  ThiefMaster May 9 '12 at 11:19
7  
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 Apr 2 '13 at 9:42
2  
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 Nov 4 '13 at 15:29
2  
Browser support details: Can I use JSON parsing –  Peter V. Mørch Jan 7 at 10:11
show 4 more comments

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 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 older browser, you can always use the JSON.parse method. This is really the ideal solution for the future.

share|improve this answer
    
Great man! I couldn't import the JSON lib, because it conflicted with other libs –  Tahir Malik Oct 1 '12 at 16:09
4  
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 Sep 10 '13 at 11:58
add comment

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);
    });
});
share|improve this answer
add comment

If you want to use json3 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 standard window.JSON object is available to you no matter what browser a client is running.

share|improve this answer
1  
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 Jan 7 at 10:14
2  
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 Jan 29 at 3:18
    
Sorry; I think you're right. Please disregard my comment as bogus. –  Peter V. Mørch Jan 30 at 4:04
    
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 Mar 10 at 1:43
add comment

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);
share|improve this answer
    
eval cant handle a json string which return as HTML –  user192344 Mar 13 '12 at 1:34
11  
IF it's html-encoded it's not JSON anymore. –  ThiefMaster May 9 '12 at 11:20
2  
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 Jul 4 '13 at 1:31
add comment

You can either use eval function as above. (Dont forget the extra braces. You will know why when you dig deep) or simply use 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

Cheers!

share|improve this answer
add comment

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 eval function. Here is the following example using eval function:

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

// Output: x, 11

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

share|improve this answer
add comment

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.

share|improve this answer
add comment

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
share|improve this answer
    
The same answer is already presented on this question. stackoverflow.com/a/16953423/2392330 –  idlerboris Apr 1 at 14:44
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.