2

I am using google maps API, and getting the response from google. Just need to get distance "text" value, e.g. 57.6 mi and duration "text" value where it is "1 hour and 1 min" from JSON that gets returned.

{
   "destination_addresses" : [ "blah blah" ],
   "origin_addresses" : [ "some address" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "57.6 mi",
                  "value" : 92652
               },
               "duration" : {
                  "text" : "1 hour 1 min",
                  "value" : 3664
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

I have tried to parse it out by using dot notation and key-value pairs, but the deepest I could get is getting "rows" - which returned me object Object.

1
  • 5
    your rows has an array (of one element) inside it. so you probably need rows[0].elements[0].distance.text Commented Oct 28, 2015 at 20:25

1 Answer 1

1

@Claies beat me to it, you can get the distance using data.rows[0].elements[0].distance.text

var data = {
  "destination_addresses": ["blah blah"],
  "origin_addresses": ["some address"],
  "rows": [{
    "elements": [{
      "distance": {
        "text": "57.6 mi",
        "value": 92652
      },
      "duration": {
        "text": "1 hour 1 min",
        "value": 3664
      },
      "status": "OK"
    }]
  }],
  "status": "OK"
}

document.write(data.rows[0].elements[0].distance.text)

Sign up to request clarification or add additional context in comments.

3 Comments

On the same token, in this syntax, data.rows[0].elements[0].distance.text, if the "rows" in the source was something else, for example, 'foo', then it would be data.foo[0].elements[0].distance.text, or is it a syntax thing?
Yes, then it would be data.foo[0].elements[0].distance.text
OK, not to be too obtuse, but if in the source "elements" was let's say "bar", then it will be data.foo[0].bar[0].distance.text - - - it's just the "elements" sounds like part of the language, but coincidentally it is a property name, so that's what threw me off. Thanks again for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.