Javascript 如何遍历 JSON obj 的属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12622744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to loop through the attributes of a JSON obj?
提问by checkmate711
Possible Duplicate:
How to loop on a JSON object?
可能的重复:
如何在 JSON 对象上循环?
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?
我试图找出如何遍历 JSON obj 的属性。我可以通过指定键来获取属性(见下文),但我如何循环遍历所有属性?
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
}
回答by Alexander Pavlov
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]);
}
}
回答by jrajav
A JSON object is just a Javascript object. If you're already using jQuery, you can use $.each() again on it to iterate over its named properties.
JSON 对象只是一个 Javascript 对象。如果你已经在使用 jQuery,你可以再次使用 $.each() 来遍历它的命名属性。
回答by Bergi
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
}
}