JavaScript json多个键

时间:2011-04-03 11:45:10

标签: javascript json

我有一个JSON var

{
"total":4,
"page":1,
"pagesize":30,
"type":"associated_user",
"items":[
{
"user_id":2727,
"site_name":"Physics",
"user_creation_date":1300894372,
"association_id":"2fbcabe5-cd42-4f5b-821e-2f1475e42ade"
},
{
"user_id":3864,
"site_name":"TeX - LaTeX",
"user_creation_date":1298808016,
"association_id":"2fbcabe5-cd42-4f5b-821e-2f1475e42ade"
},
{
"user_id":5983,
"site_name":"Stack Apps",
"user_creation_date":1301323608,
"association_id":"2fbcabe5-cd42-4f5b-821e-2f1475e42ade"
},
{
"user_id":6260,
"site_name":"English Language and Usage",
"user_creation_date":1300449905,
"association_id":"2fbcabe5-cd42-4f5b-821e-2f1475e42ade"
}
]
}

如您所见,site_name块中有四个items个键。我只能使用items[0].site_name访问第一个但是如何逐个访问其他三个?

3 个答案:

答案 0 :(得分:1)

获取所有网站名称

您需要运行while loop才能动态执行

var i=0
while(i<items.length){

var site_name=items[i].site_name;
}

答案 1 :(得分:1)

问候    如果我让你正确,那么你需要像这样循环遍历对象数组

var obj ={
"total":4,
"page":1,
"pagesize":30,
"type":"associated_user",
"items":[
{
"user_id":2727,
"site_name":"Physics",
"user_creation_date":1300894372,
"association_id":"2fbcabe5-cd42-4f5b-821e-2f1475e42ade"
},
{
"user_id":3864,
"site_name":"TeX - LaTeX",
"user_creation_date":1298808016,
"association_id":"2fbcabe5-cd42-4f5b-821e-2f1475e42ade"
},
{
"user_id":5983,
"site_name":"Stack Apps",
"user_creation_date":1301323608,
"association_id":"2fbcabe5-cd42-4f5b-821e-2f1475e42ade"
},
{
"user_id":6260,
"site_name":"English Language and Usage",
"user_creation_date":1300449905,
"association_id":"2fbcabe5-cd42-4f5b-821e-2f1475e42ade"
}
]
};

var objItems = obj.items;
for(var i=0;i<objItems .length;i++)
{
alert(obj.items[i].site_name);
}

答案 2 :(得分:0)

您可以使用jquery轻松完成此操作:

$(jsonvar).each(function(){
    tempvar = this.site_name;
});

然后,这将循环存储'tempvar'

中所需段的项目