从嵌套的JSON Node JS

时间:2017-07-05 11:27:17

标签: javascript json node.js traversal

我需要提取距离和持续时间的 text 值,但不幸的是我无法遍历JSON。有关如何以最简单的方式遍历Node JS中的节点的任何想法?

     {
   "destination_addresses" : [ "Chennai, Tamil Nadu, India" ],
   "origin_addresses" : [ "Kolkata, West Bengal, India" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "1,671 km",
                  "value" : 1671269
               },
               "duration" : {
                  "text" : "1 day 5 hours",
                  "value" : 104370
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
} 

1 个答案:

答案 0 :(得分:0)

假设您的JSON是对象命名数据

var data =     {
   "destination_addresses" : [ "Chennai, Tamil Nadu, India" ],
   "origin_addresses" : [ "Kolkata, West Bengal, India" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "1,671 km",
                  "value" : 1671269
               },
               "duration" : {
                  "text" : "1 day 5 hours",
                  "value" : 104370
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
} 

您可以像这样访问距离元素

data.rows[0].elements[0].distance