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"

}

]

}

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

到目前为止,我有以下jQuery代码:

$.get('forums.php', function(json, textStatus) {

//optional stuff to do after success

alert(textStatus);

alert(json);

});

我该如何使用jQuery?

回答:

{}在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在其“幕后”所做的工作。希望这可以帮助。

以上是 jQuery解析JSON多维数组 的全部内容, 来源链接: utcz.com/qa/426911.html

回到顶部