美好的一天,
这是我的API中的示例响应,我对结果感到有点困惑。 items数组中有多个对象,我希望得到来自API的特定响应。我的问题是如何在JSON中获取多个键中的多个值?
Name: Puregold Meycauyan,
formattedAddress: "Meycauayan, Bulacan, Bulacan, Pilipinas",
Tips: This grocery opens early and the lines are never long.
我只会获得venue.name,venue.formattedAddress和tips.text?
我的预期是:
{{1}}
答案 0 :(得分:1)
您可以使用解构赋值来获取并将数组或对象的特定元素分配给变量标识符
let items = [{"venue":{"id":"4e82750f8b8185a7c93d3632","name":"Puregold Meycauyan","contact":{},"location":{"crossStreet":"Meycauayan","lat":14.72670029378359,"lng":120.96040348293954,"labeledLatLngs":[{"label":"display","lat":14.72670029378359,"lng":120.96040348293954}],"cc":"PH","city":"Bulacan","state":"Bulacan","country":"Pilipinas","formattedAddress":["Meycauayan","Bulacan","Bulacan","Pilipinas"]},"tips":[{"id":"4f656942e4b08b4770548244","createdAt":1332046146,"text":"This grocery opens early and the lines are never long.","type":"user","canonicalUrl":"https://foursquare.com/item/4f656942e4b08b4770548244"}]}}];
let {name:_name, location:{formattedAddress}, tips:[{text}]} = items[0].venue;
console.log(_name, formattedAddress, text);

答案 1 :(得分:0)
您需要确保您的json包装在大括号中,以及数组中的嵌套对象。 E.G。
var json = {
"items": [{
"venue": {
"id": "4e82750f8b8185a7c93d3632",
"name": "Puregold Meycauyan",
"contact": {}
}
}]
}
console.log(json.items[0].venue.name);
答案 2 :(得分:0)
获得预期输出的方法可以按如下方式完成:
var json = {
items: [{
"venue": {
"id": "4e82750f8b8185a7c93d3632",
"name": "Puregold Meycauyan",
"contact": {
},
"location": {
"crossStreet": "Meycauayan",
"lat": 14.72670029378359,
"lng": 120.96040348293954,
"labeledLatLngs": [{
"label": "display",
"lat": 14.72670029378359,
"lng": 120.96040348293954
}],
"cc": "PH",
"city": "Bulacan",
"state": "Bulacan",
"country": "Pilipinas",
"formattedAddress": ["Meycauayan",
"Bulacan",
"Bulacan",
"Pilipinas"]
},
"tips": [{
"id": "4f656942e4b08b4770548244",
"createdAt": 1332046146,
"text": "This grocery opens early and the lines are never long.",
"type": "user",
"canonicalUrl": "https://foursquare.com/item/4f656942e4b08b4770548244",
}]
}
}]
};
console.log("Name: " + json.items[0].venue.name + ",\n" +
"formattedAddress: \"" + json.items[0].venue.location.formattedAddress.toString() + "\",\n" +
"Tips: " + json.items[0].venue.tips[0].text);