sinusGob
sinusGob

Reputation: 4313

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?

Upvotes: 0

Views: 60

Answers (2)

mitsos1os
mitsos1os

Reputation: 2290

Correctly as Simon said. You could also set an options object in your request call with { json: true } and response body would be automatically parsed to json

Upvotes: 0

Simon Kirsten
Simon Kirsten

Reputation: 2577

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.

Upvotes: 1

Related Questions