如何在JSON中选择此值?

时间:2016-06-18 19:24:56

标签: json

我正在尝试从以下JSON代码返回数组"value"中的术语"distance"的值:

{
   "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"
            }
}

为此,我尝试使用代码rows.elements.distance.value来选择它,但这不会返回值。我为什么遇到这个问题?

1 个答案:

答案 0 :(得分:0)

注意elements是一个数组

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]);