Parse JSON in JavaScript?

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?

Text Copied From stackoverflow.com
on : Tue, Feb 08, 2011 Views : 1718632

Accepted Answer

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.

Text Copied From stackoverflow.com
on : Tue, Feb 08, 2011

Ask Question

If you want to ask question you must LogIn or SignUp
Login SignUp

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp