使用 jquery 循环遍历 json 对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6191646/
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
looping over a json object array with jquery
提问by sharpiemarker1
Im trying to loop through a json files' object array to access its variables' keys and values and append them to list items using jquery's getjson and each.
我试图遍历 json 文件的对象数组以访问其变量的键和值,并使用 jquery 的 getjson 和 each 将它们附加到列表项。
I think the solution should be similar to the solution in this article... but I cant seem to make it work and display the results at all... Any help would be very much appreciated!
我认为解决方案应该与本文中的解决方案类似......但我似乎无法让它工作并显示结果......任何帮助将不胜感激!
Jquery, looping over a json array
$.getJSON('data/file.json', function(data)
{
var data = [];
$(data).each(function(idx, obj)
{
$(obj).each(function(key, value)
{console.log(key + ": " + value);}
}
}
);
The json data is formatted like this:
json 数据格式如下:
[{
"name": "Name",
"street_address1": "XYZ Road",
"street_address2": null,
"city": "New York",
"zip": 10038,
"phone": 2122222222 ",
"description ": "About xyz..."
},
{ next listing... }]
And the html should be formatted like this:
并且 html 的格式应该是这样的:
Name: Name
Address: XYZ Road
Floor #2
City, State 10001
Description: About xyz...
回答by Rocket Hazmat
var data = [];
var data = [];
You are replacing data
with a blank array, thus destroying your data when this is ran. Remove this line, and it should work.
您正在替换data
为一个空白数组,从而在运行时破坏您的数据。删除此行,它应该可以工作。
EDIT: There are also some syntax errors in your code. You need to close the parenthesis after each of the each
statements. It should look like this:
编辑:您的代码中也存在一些语法错误。您需要在每个each
语句之后关闭括号。它应该是这样的:
$.getJSON('data/file.json', function(data){
$(data).each(function(idx, obj){
$(obj).each(function(key, value){
console.log(key + ": " + value);
});
});
});
EDIT 2: data
and obj
aren't jQuery objects, they are just normal objects. You need to use $.each
compared to $().each
for this.
编辑 2:data
并且obj
不是 jQuery 对象,它们只是普通对象。为此,您需要使用$.each
相比$().each
。
$.getJSON('data/file.json', function(data){
$.each(data, function(idx, obj){
$.each(obj, function(key, value){
console.log(key + ": " + value);
});
});
});
回答by AlexC
$.getJSON('data/file.json', function(data){
$.each(data,function(idx, obj){
$.each(obj, function(key, value){
console.log(key + ": " + value);
});
});
});
回答by Micha?l Witrant
The code has multiple syntax errors. Check it on http://www.jslint.com/for example.
代码有多个语法错误。例如,在http://www.jslint.com/上检查它。