Search A2Z 24

Question : Parse JSON in JavaScript?

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

var response = '{"name":"xyz","age":20}';

How can I get the values of name and age from this?

asked December 22, 2014

1 Answers

Dispalying 1 to 1 of 1 |

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 = '{"name":"xyz","age":20}',
	obj = JSON.parse(json);
	alert(obj.name+'    '+obj.age);

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

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 = '{"name":"xyz","age":20}',
    obj = JSON && JSON.parse(json) || $.parseJSON(json);
	alert(obj.name+'    '+obj.age);

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.

Note : If you are getting this from(data) an outside site (third party 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(obj.name+'    '+obj.age);
    $.each(json, function (i, ele) {
        alert(ele.name+'    '+ele.age);
See comments (0) | Comment
Answered 2 Years ago
Dispalying 1 to 1 of 1 |

Write your Answer write code <pre class="brush: xml">---code---</pre>

Login as a member to access answering block !! click-here

Reveal Modal Goodness

This is a default modal in all its glory, but any of the styles here can easily be changed in the CSS.

This is just a simple modal with the default styles, but any type of content can live in here. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi quis sem vel enim eleifend tristique. Etiam tincidunt faucibus pharetra.