jQuery解析JSON多维数组 [英] jQuery parse JSON multidimensional array

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

问题描述

我有一个这样的 JSON 数组:

I have a JSON array like this:

{
  "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 来返回每个数组值的值,但我不确定如何访问它们.

I want to use jQuery .getJSON to be able to return the values of each of the array values, but I'm not sure as to how to get access to them.

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

So far I have this jQuery code:

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

        });

我如何用 jQuery 做到这一点?

How can I do this with jQuery?

推荐答案

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

The {} in JSON represents an object. Each of the object's properties is represented by key:value and comma separated. The property values are accessible by the key using the period operator like so json.forum. The [] in JSON represents an array. The array values can be any object and the values are comma separated. To iterate over an array, use a standard for loop with an index. To iterate over object's properties without referencing them directly by key you could use for in loop:

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..
    }
}

如果您想以 jQuery 风格的方式执行此操作,请获取 $.each():

If you want to do this the jQueryish way, grab $.each():

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

我使用了与普通 JavaScript"方式相同的变量名,以便您更好地理解 jQuery 用它在幕后"做了什么.希望这会有所帮助.

I've used the same variable names as the "plain JavaScript" way so that you'll understand better what jQuery does "under the hoods" with it. Hope this helps.

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

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