使用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);} } } ); 

json数据的格式如下:

 [{ "name": "Name", "street_address1": "XYZ Road", "street_address2": null, "city": "New York", "zip": 10038, "phone": 2122222222 ", "description ": "About xyz..." }, { next listing... }] 

并且html应该格式化如下:

  Name: Name Address: XYZ Road Floor #2 City, State 10001 Description: About xyz... 

var data = [];

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

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

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

编辑2dataobj不是jQuery对象,它们只是普通对象。 你需要使用$.each$().each相比较。

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

该代码有多个语法错误。 例如, 请访问http://www.jslint.com/进行检查。