JSON.parse从JSON返回[object]

时间:2015-10-22 13:31:40

标签: node.js

我正在使用名为request的npm包向https://maps.googleapis.com/maps/api/geocode/json?address=Jur%C4%8Dkova+cesta+225&key=AIzaSyChkPdCaAaVZwYof8ZbKspokuYt41NlJ_0发送http请求

现在我想解析收到的数据,以便提取LAT / LONG并将其写入我的数据库。但到目前为止,我得到的所有输出都是:

[ { address_components:
     [ [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object] ],
    formatted_address: 'Breznikova ulica 15, 1230 Domžale, Slovenia',
    geometry:
     { location: [Object],
       location_type: 'ROOFTOP',
       viewport: [Object] },
    place_id: 'ChIJR2mtdUc0ZUcRv5nXK0zEx7M',
    types: [ 'street_address' ] },
  { address_components:
     [ [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object] ],
    formatted_address: 'Breznikova ulica 15, 1000 Ljubljana, Slovenia',
    geometry:
     { location: [Object],
       location_type: 'ROOFTOP',
       viewport: [Object] },
    place_id: 'ChIJ19Ax9OPMekcRoPvkJ6SKNEg',
    types: [ 'street_address' ] },
  { address_components:
     [ [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object] ],
    formatted_address: 'Breznikova ulica 15, 2000 Maribor, Slovenia',
    geometry:
     { location: [Object],
       location_type: 'ROOFTOP',
       viewport: [Object] },
    place_id: 'ChIJDUicXFd2b0cRYrf99vgTPBs',
    types: [ 'street_address' ] } ]

这是我的代码的摘录,它从我的server.js文件生成:

//get lat and long before saving from gmaps API
//build gmaps API URL
var urlAddress = shop.address.replace(/ /gi, '+');
var urlAPIKey = '&key=AIzaSyChkPdCaAaVZwYof8ZbKspokuYt41NlJ_0';
var url = 'https://maps.googleapis.com/maps/api/geocode/json?address=';
url = url.concat(urlAddress).concat(urlAPIKey);
//make a request
request({
    uri: url,
    method:"GET",
    timeout: 100000
    }, function(error, response, body) {
        var gmaps = JSON.parse(body);
        console.log(gmaps.results);
});

如果有人能够指出我做错了什么就会很棒。如果我尝试输出对象,则只返回undefined。

1 个答案:

答案 0 :(得分:1)

它出现为[Object]的原因是为了便于阅读,如果要显示结果的完整转储,则必须先将其传递给JSON.stringify。

至于访问address_components,结果是一个数组,因此您必须为该数组的特定元素访问它们(例如gmaps.results[0].address_components