几乎可以肯定这是最基本的东西,但是我无法一生解决问题。我有一个从Google Maps 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
它返回未定义。我以为这可能与异步问题有关,但是我不能打印数据变量,但不能单独打印其属性
答案 0 :(得分:0)
您首先需要将其解析为JSON
var obj = JSON.parse(data);
console.log(obj.destination_addresses);