从API接收的JSON中提取数据

时间:2018-02-22 13:16:02

标签: json node.js api web-services

所以我目前正在使用我想要从中提取数据的API。它返回给我的JSON是这样的:

{
"Jax":{"id":24,"key":"Jax","name":"Jax","title":"Grandmaster at Arms"},
"Sona":{"id":37,"key":"Sona","name":"Sona","title":"Maven of the Strings"},
"Tristana":{"id":18,"key":"Tristana","name":"Tristana","title":"the Yordle Gunner" }
}

我想提取 id 名称属性并创建一个数组,如下所示:

[
{name:"Jax",id:24},
{name:"Sona",id:37},
{name:"Tristana",id:18},
]

感觉就像我从API收到的JSON质量差,我希望这样:

{"list":{
{"id":24,"key":"Jax","name":"Jax","title":"Grandmaster at Arms"},
{"id":37,"key":"Sona","name":"Sona","title":"Maven of the Strings"},
{"id":18,"key":"Tristana","name":"Tristana","title":"the Yordle Gunner"}
}

有任何建议如何解决我的问题?

1 个答案:

答案 0 :(得分:2)

您可以按以下方式枚举属性:

var list = [];
for(var prop in jsonObj) {
  if(jsonObj.hasOwnProperty(prop)) {
    list.push({name: jsonObj[prop].name, id: jsonObj[prop].id});
  }
}