使用jquery循环遍历json对象数组

sha*_*er1 3 jquery json

我试图循环一个json文件的对象数组来访问它的变量的键和值,并使用jquery的getjson和每个列表将它们附加到列表项.

我认为解决方案应该类似于本文中的解决方案...但我似乎无法使其工作并显示结果...任何帮助将非常感谢!

Jquery,循环遍历json数组

$.getJSON('data/file.json', function(data)
 { 
   var data = [];
   $(data).each(function(idx, obj)
    { 
     $(obj).each(function(key, value)
      {console.log(key + ": " + value);}
     }
   }
);
Run Code Online (Sandbox Code Playgroud)

json数据的格式如下:

[{
    "name": "Name",
    "street_address1": "XYZ Road",
    "street_address2": null,
    "city": "New York",
    "zip": 10038,
    "phone": 2122222222 ", 
    "description ": "About xyz..."
 }, 
 { next listing... }]
Run Code Online (Sandbox Code Playgroud)

并且html应该格式化如下:

 Name: Name

 Address: XYZ Road
          Floor #2
          City, State 10001

 Description: About xyz...
Run Code Online (Sandbox Code Playgroud)

Roc*_*mat 12

var data = [];

您正在替换data为空白数组,因此在运行此数据时会破坏您的数据.删除这一行,它应该工作.

编辑:您的代码中也存在一些语法错误.您需要在每个each语句后关闭括号.它应该如下所示:

$.getJSON('data/file.json', function(data){ 
    $(data).each(function(idx, obj){ 
        $(obj).each(function(key, value){
            console.log(key + ": " + value);
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

编辑2:dataobj不是jQuery的对象,他们只是普通的对象.你需要使用$.each$().each此相比.

$.getJSON('data/file.json', function(data){ 
    $.each(data, function(idx, obj){ 
        $.each(obj, function(key, value){
            console.log(key + ": " + value);
        });
    });
});
Run Code Online (Sandbox Code Playgroud)