我正在使用英特尔XDK编写应用程序,我正在使用Wordpress API来获取用户信息。该网址产生以下内容:
{"status":"ok","0":{"id":2,"username":"testshop","shopname":"shopname","url":"","displayname":"testshop","nickname":"Test Shop","avatar":"80","longitude":"54.5591894,-1.237610600000039","gender":"Menswear","mensCats":"Tech Geek| Indie Lad| Vintage Gent| Casual Bloke","womensCats":""},"1":{"id":3,"username":"testShop2","shopname":"","url":"","displayname":"testShop2","nickname":"Test Shop 2","avatar":"","longitude":"54.5576249,-1.2475360999999338","gender":"Womenswear","mensCats":"","womensCats":"Indie Babe| Vintage Queen"}}
我有另一个API调用,在调用时,只返回一个数组,我可以正常访问此信息,因为我不需要循环。但是,我不知道如何循环以上。下面是我用来获取JSON的代码:
$.getJSON(url, function(json){
var name = json.nickname;
}
任何人都可以帮助您了解迭代数据的最佳方法。
谢谢
答案 0 :(得分:0)
由于您的代码不生成数组而是生成对象,因此您可以执行以下操作:
$.getJSON(url, function(json){
if(json.status === "ok")
{
var keys = Object.keys(json).filter(function(str){ return str !== "status" });
for(var i = 0 ; i < keys.length; i++)
{
console.log(json[keys[i]]);
}
}
}