用jQuery循环遍历JSON对象数组 [英] looping over a json object array with jquery

查看:74
本文介绍了用jQuery循环遍历JSON对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图遍历json文件的对象数组以访问其变量的键和值,并使用jquery的getjson及其每个将它们附加到列表项中.

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.

我认为解决方案应该与本文中的解决方案相似...但是我似乎无法使其完全起作用并显示结果...任何帮助将不胜感激!

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,遍历json数组

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

json数据的格式如下:

The json data is formatted like this:

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

并且html的格式应如下:

And the html should be formatted like this:

 Name: Name

 Address: XYZ Road
          Floor #2
          City, State 10001

 Description: About xyz...

推荐答案

var data = [];

您要用空白数组替换data,从而在运行时破坏数据.删除此行,它应该可以工作.

You are replacing data with a blank array, thus destroying your data when this is ran. Remove this line, and it should work.

编辑:您的代码中还有一些语法错误.您需要在每个each语句之后关闭括号.它应该看起来像这样:

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:

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

编辑2 :dataobj不是jQuery对象,它们只是普通对象.与 $.each /> $().each .

EDIT 2: data and obj aren't jQuery objects, they are just normal objects. You need to use $.each compared to $().each for this.

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

这篇关于用jQuery循环遍历JSON对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆