这几乎肯定会是超级基本的东西,但我一生都无法弄清楚出了什么问题。我有一个从谷歌地图 JS API 返回的数据对象
{
"destination_addresses" : [ "12 Ansell Rd, London SW17, UK" ],
"origin_addresses" : [
"911 Alfreds Way, Barking IG11 0AX, UK",
"911 Alfreds Way, Barking IG11 0AX, UK",
"50 Buttesland St, Hoxton, London N1 6BY, UK"
],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "24.4 km",
"value" : 24411
},
"duration" : {
"text" : "55 mins",
"value" : 3297
},
"duration_in_traffic" : {
"text" : "58 mins",
"value" : 3454
},
"status" : "OK"
}
]
},
{
"elements" : [
{
"distance" : {
"text" : "24.4 km",
"value" : 24411
},
"duration" : {
"text" : "55 mins",
"value" : 3297
},
"duration_in_traffic" : {
"text" : "58 mins",
"value" : 3454
},
"status" : "OK"
}
]
},
{
"elements" : [
{
"distance" : {
"text" : "13.9 km",
"value" : 13905
},
"duration" : {
"text" : "48 mins",
"value" : 2909
},
"duration_in_traffic" : {
"text" : "45 mins",
"value" : 2717
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
我正在使用带有require的https模块的.get检索它,它工作绝对正常,然后我像这样打印数据......
https.get(`https://maps.googleapis.com/maps/api/distancematrix/json?origins=51.5285,0.0847|51.5285,0.0847|51.5285,-0.0847&destinations=51.432622,-0.164496&departure_time=now&key=APIKEY`, (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
//When all data is received
resp.on('end', () => {
console.log(data);
});
});
问题是一旦我尝试访问(甚至只是控制台日志(对象中的任何数据,例如
data.destination_addresses
它返回未定义。我认为这可能与异步问题有关,但是我可以单独打印数据变量但不能打印其属性是没有意义的
您需要先将其解析为 JSON
var obj = JSON.parse(data);
console.log(obj.destination_addresses);