jQuery解析JSON多维数组

时间:2010-03-21 16:47:40

标签: jquery json arrays

我有一个像这样的JSON数组:

{
  "forum":[
    {
      "id":"1",
      "created":"2010-03-19 ",
      "updated":"2010-03-19 ","user_id":"1",
      "vanity":"gamers",
      "displayname":"gamers",
      "private":"0",
      "description":"All things gaming",
      "count_followers":"62",
      "count_members":"0",
      "count_messages":"5",
      "count_badges":"0",
      "top_badges":"",
      "category_id":"5",
      "logo":"gamers.jpeg",
      "theme_id":"1"
    }
  ]
}

我想使用jQuery .getJSON来返回每个数组值的值,但我不确定如何访问它们。

到目前为止,我有这个jQuery代码:

$.get('forums.php', function(json, textStatus) {
            //optional stuff to do after success
            alert(textStatus);
            alert(json);

        });

如何使用jQuery执行此操作?

2 个答案:

答案 0 :(得分:59)

JSON中的{}表示一个对象。每个对象的属性由key:value表示,并以逗号分隔。使用句点运算符(例如json.forum)可以通过键访问属性值。 JSON中的[]表示一个数组。数组值可以是任何对象,值以逗号分隔。要迭代数组,请使用带索引的标准for循环。要迭代对象的属性而不直接通过键引用它们,您可以使用for in循环:

var json = {"forum":[{"id":"1","created":"2010-03-19 ","updated":"2010-03-19 ","user_id":"1","vanity":"gamers","displayname":"gamers","private":"0","description":"All things gaming","count_followers":"62","count_members":"0","count_messages":"5","count_badges":"0","top_badges":"","category_id":"5","logo":"gamers.jpeg","theme_id":"1"}]};

var forum = json.forum;

for (var i = 0; i < forum.length; i++) {
    var object = forum[i];
    for (property in object) {
        var value = object[property];
        alert(property + "=" + value); // This alerts "id=1", "created=2010-03-19", etc..
    }
}

如果你想以jQueryish的方式做到这一点,请抓住$.each()

$.each(json.forum, function(i, object) {
    $.each(object, function(property, value) {
        alert(property + "=" + value);
    });
});

我使用了与“普通JavaScript”相同的变量名称,这样你就可以更好地理解jQuery在“引擎盖下”做什么。希望这会有所帮助。

答案 1 :(得分:0)

这应该可以正常工作。只需使用$.getJSON代替$.get