Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through the attributes of a JSON obj? [duplicate]

Possible Duplicate:
How to loop on a JSON object?

I'm trying to find out how to loop through the attributes of a JSON obj. I can get the attributes by specifying the key (see below), but how do I just loop 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

}
like image 379
checkmate711 Avatar asked Sep 27 '12 13:09

checkmate711


People also ask

How do I iterate through a JSON object?

Use Object.values() or Object. entries(). These will return an array which we can then iterate over. Note that the const [key, value] = entry; syntax is an example of array destructuring that was introduced to the language in ES2015.

Can you loop through JSON?

Looping Using JSON It's a light format for storing and transferring data from one place to another. So in looping, it is one of the most commonly used techniques for transporting data that is the array format or in attribute values. Here's an example that demonstrates the above concept.

How do I iterate through a JSON object in node?

Iterating Over JSON With Root Node Inside your React app, create a data. js file and export the above response as an object. Note that both images and users are arrays, so you can use the map() method in JSX to iterate over them as shown below. You can also use regular for loops.

How JSON array looks like?

A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.


1 Answers

for (var name in json_parsed) {
    console.log(name + "=" + json_parsed[name]);
}

If you need to check if the corresponding property is defined on the object in question, not on some of those on the prototype chain (this is ridiculous 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 all array objects' attributes, 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]);
    }
}
like image 192
Alexander Pavlov Avatar answered Sep 18 '22 14:09

Alexander Pavlov