jQuery解析JSON多维数组

Chr*_*sMJ 21 arrays jquery json

我有一个像这样的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"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

        });
Run Code Online (Sandbox Code Playgroud)

我怎么能用jQuery做到这一点?

Bal*_*usC 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..
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你想以jQueryish方式执行此操作,请抓住$.each():

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

我使用了相同的变量名称作为"普通JavaScript"方式,这样你就可以更好地理解jQuery在"引擎盖下"做什么.希望这可以帮助.