home

Search A2Z 24

JQuery Loop Over JSON String – $.Each Example

Review a simple jQuery example to loop over a JavaScript array object.

var json = [
	{"id":"1","tagName":"apple"},
	{"id":"2","tagName":"orange"},
	{"id":"3","tagName":"banana"},
	{"id":"4","tagName":"watermelon"},
	{"id":"5","tagName":"pineapple"}
];

$.each(json, function(idx, obj) {
	alert(obj.tagName);
});

Above code snippet is working fine, prompts the “apple”, “orange” … as expected.

Problem : JSON string 

Review below example, declares a JSON string (enclosed with single or double quotes) directly.

var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
{"id":"5","tagName":"pineapple"}]';

$.each(json, function(idx, obj) {
	alert(obj.tagName);
});

In Chrome, it shows following errors in console :

Uncaught TypeError: Cannot use 'in' operator to search for '156' 
in [{"id":"1","tagName":"apple"}...

Solution : Convert JSON string to JavaScript object

To fix it, converts it to Javascript object via standard JSON.parse() or jQuery $.parseJSON.

var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
{"id":"5","tagName":"pineapple"}]';

$.each(JSON.parse(json), function(idx, obj) {
	alert(obj.tagName);
});
 
//or 
 
$.each($.parseJSON(json), function(idx, obj) {
	alert(obj.tagName);
});

Note : Most web applications will return JSON formatted string directly, you need to convert it to JavaScript object before parse it with jQuery.

About Author

loading...

Share your thoughts!

Login as a member to access comment posting block !! click-here

Thoughts From Other Users (0)

No Comments

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.

×