简体   繁体   English

如何使用javascript从api读取JSON数据

[英]how to read JSON data from the api with javascript

结果之后 Hello I'm trying to read JSON data from an api but it doesn't work when I try to get data from that api works fine and when I try to get the distance value I get undefined.Please help您好,我正在尝试从 api 读取 JSON 数据,但是当我尝试从该 api 获取数据时它不起作用,当我尝试获取距离值时,我得到未定义的值。请帮忙

The code编码

fetch('https://maps.googleapis.com/maps/api/distancematrix/json?units=meter&origins=Gurd%20Shola%201%20Station,%20Addis%20Ababa&destinations=Bole%20Medhane%20Alem%20Church,%20Addis%20Ababa&key=API_KEY')
  .then(response => {
    return response.json()
  })
  .then(data => {
// Work with JSON data here
console.log(data.rows.elements.distance.value)
 })
  .catch(err => {

 })

the result from the web is just like this网上的结果是这样的

{
   "destination_addresses" : [ "Addis Ababa, Ethiopia" ],
   "origin_addresses" : [ "Addis Ababa, Ethiopia" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "6.4 km",
                  "value" : 6386
               },
               "duration" : {
                  "text" : "15 mins",
                  "value" : 901
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

Change data.rows.elementes.distance.value to data.rows[0].elements[0].distance.value ..变化data.rows.elementes.distance.valuedata.rows[0].elements[0].distance.value ..

Check for typo here it is elements and not elementes ..检查这里是否有错字,它是elements不是elementes ..

Also rows and elements is an array and if you need to get the distance then you need to get it like rows[0].elements[0].distance .. rowselements也是一个数组,如果你需要得到距离,那么你需要得到它,比如rows[0].elements[0].distance ..

 const data = { "destination_addresses" : [ "Addis Ababa, Ethiopia" ], "origin_addresses" : [ "Addis Ababa, Ethiopia" ], "rows" : [ { "elements" : [ { "distance" : { "text" : "6.4 km", "value" : 6386 }, "duration" : { "text" : "15 mins", "value" : 901 }, "status" : "OK" } ] } ], "status" : "OK" } console.log(data.rows[0].elements[0].distance);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM