0

I'm trying to return the value of the term "value" within the array "distance" from the following JSON code:

{
   "destination_addresses" : [ "San Francisco, CA, USA", "Victoria, BC, Canada" ],
   "origin_addresses" : [ "Vancouver, BC, Canada", "Seattle, WA, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "1,529 km",
                  "value" : 1528699
               },
               "duration" : {
                  "text" : "14 hours 56 mins",
                  "value" : 53778
               },
               "status" : "OK"
            }
}

To do this, I've tried using the code rows.elements.distance.value to select it, but this does not return a value. Why am I having this problem?

John Smith
  • 359
  • 3
  • 13
  • 2
    Do you mean select it in JavaScript? JSON is a data format, not a programming language. Also, questions seeking debugging help ("**why isn't this code working?**") must include the desired behavior, a *specific problem or error* and *the shortest code necessary* to reproduce it **in the question itself**. Questions without **a clear problem statement** are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example.](http://stackoverflow.com/help/mcve) – elixenide Jun 18 '16 at 19:27
  • 1
    `rows[0].elements[0].distance.value` – James Buck Jun 18 '16 at 19:28
  • Thanks for the response James. I've tried using your code to print the desired value on a webpage, but it has not worked. Can yo understand why this might be? My attempt to do this used the code `document.getElementById("demo").innerHTML = rows[0].elements[0].distance.value` with `

    `.
    – John Smith Jun 18 '16 at 19:42

1 Answers1

0

Pay attention that elements is an array

var jsonstring = '{"destination_addresses":["San Francisco, CA, USA","Victoria, BC, Canada"],"rows":[{"elements":[{"distance":{"text":"1,529 km","value":1528699},"duration":{"text":"14 hours 56 mins","value":53778},"status":"OK"}]}]}';

var parsed = JSON.parse(jsonstring);

console.log(parsed.rows[0].elements[0]);
D.Dimitrioglo
  • 3,413
  • 2
  • 21
  • 41