sinusGob sinusGob - 5 months ago 19
Node.js Question

How do i read these json data?

I know this sounds absurd, but I've been trying to read these json data from google maps api, but seems like none of it works

Here's the code

app.get('/distance', function(req, res, next) {
request('https://maps.googleapis.com/maps/api/distancematrix/json?origins=Seattle&destinations=San+Francisco&key=' + config.GOOGLE_DISTANCE_API, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}


});
});


body will return this data

{
"destination_addresses" : [ "New York, NY, USA" ],
"origin_addresses" : [ "Washington, DC, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "225 mi",
"value" : 361715
},
"duration" : {
"text" : "3 hours 49 mins",
"value" : 13725
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}


When I try to console.log
body.destination_addresses
and as well as
body.rows
and it all shows undefined. How do i access it?

Answer

You first need to parse the json data:

var obj = JSON.parse(body);

now you can access obj.destination_addresses etc.

If you are using jquery use the $.getJSON method wich will get and parse the json for you.