我正在向我的服务器发送 http 请求(使用 ajax),它返回 json 字符串,如下所示:
{
"neighbors":{
"data":[
{
"id":"7f40cb24-603e-4943-9a0b-e16e024c8bd5",
"name":"jeff ferry",
"picture":"url",
"location":{
"data":[
{
"latitude":"xxx",
"longitude":"yyy"
}
]
}
}
]
}
}
在 html 页面 ajax 回调中,我正在访问如下数据:
success: function (data) {
var outerObj = data.neighbor.data;
var res = "";
for (i in outerObj )
{
if (outerObj .hasOwnProperty(i)) {
// my outer stuff
var innerObj = outerObj.data;
for (j in innerObj)
{
// my inner stuff
if (innerObj.hasOwnProperty(j)) {
}
}
}
}
}
但我想知道我是否可以通过某种优化(更短)的方式访问它?
任何明显的帮助
最佳答案
也许你可以加强从服务器返回的数据结构?由于 1) 位置属性实际上只是一个纬度/经度元组,2) 内部 data
数组周围的对象只是一个冗余包装器,这样怎么样:
{
"neighbors":[
{
"id":"7f40cb24-603e-4943-9a0b-e16e024c8bd5",
"name":"jeff ferry",
"picture":"url",
"location":["xxx","yyy"]
}
]
}
这样,你的 JavaScript 就会变成这样:
success: function (data) {
var res = ""; // what was this for, anyway?
for (var n in data.neighbors) if (data.neighbors.hasOwnProperty(n) {
var neighbor = data.neighbors[n];
// actions on the neighbor object here
var location = neighbor.location;
// actions on the location here
}
}
关于javascript - 使用 javascript 优化解析(提取)json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13621359/