How to iterate over the attributes of a JSON object?

Possible duplicate:
How to loop on a JSON object?

I am trying to figure out how to iterate over the JSON attributes of obj. I can get the attributes by specifying the key (see below), but how can I just go through all of them?

var jsonStr = '{"Items":[{"Title": "Title 1", "Description":"Description 1"}]}'; var json_parsed = $.parseJSON(jsonStr); // Cycle through all list items $.each(json_parsed.Items, function(i, val) { var listItem = $(this); var title = listItem.attr('Title'); var description = listItem.attr('Description'); // Instead, loop through all attributes } 
+8
json javascript jquery
source share
3 answers
 for (var name in json_parsed) { console.log(name + "=" + json_parsed[name]); } 

If you need to check whether the corresponding property is defined for the object in question, and not for some of them in the prototype chain (this is funny for the case in question, but still useful), you can add this check:

 if (json_parsed.hasOwnProperty(name)) console.log(name + "=" + json_parsed[name]); 

EDIT

To actually iterate over the attributes of all objects in an array, use this snippet:

 var items = json_parsed.Items; for (var i = 0; i < items.length; ++i) { console.log("Item #" + i); for (var name in items[i]) { console.log(name + "=" + items[i][name]); } } 
+16
source share

A JSON object is just a Javascript object. If you are already using jQuery, you can again use $ .each () to repeat named properties.

+2
source share
 var jsonStr = '{"Items":[{"Title": "Title 1", "Description":"Description 1"}]}'; var json_parsed = JSON.parse(jsonStr); var items = json_parsed.Items; // an array for (var i=0; i<items.length; i++) { // loop over it var listItem = items[i]; // an object for (var prop in listItem) { // enumerate its property names // prop is "Title", "Description" etc listItem[prop] // is the respective value } } 
+1
source share

All Articles