【问题标题】:How to read an JSON array如何读取 JSON 数组
【发布时间】:2022-01-01 07:44:05
【问题描述】:

如何使用纯 javascript 读取 JSON 数组?

我需要读取的数组示例:

{
  "GetRouteSummaryForStopResult": {
    "StopNo": "1234",
    "Error": "",
    "StopDescription": "STREET 1 / STREET 2",
    "Routes": {
      "Route": {
        "RouteNo": "1234",
        "RouteHeading": "END_POINT",
        "DirectionID": 1,
        "Direction": "",
        "Trips": {
          "Trip": [
            {
              "Longitude": "-75",
              "Latitude": "45",
              "GPSSpeed": "",
              "TripDestination": "END_POINT",
              "TripStartTime": "10:30",
              "AdjustedScheduleTime": "9",
              "AdjustmentAge": "0.48",
              "LastTripOfSchedule": false,
              "BusType": "NFIN"
            },
            {
              "Longitude": "",
              "Latitude": "",
              "GPSSpeed": "",
              "TripDestination": "END_POINT",
              "TripStartTime": "11:00",
              "AdjustedScheduleTime": "29",
              "AdjustmentAge": "-1",
              "LastTripOfSchedule": false,
              "BusType": ""
            }
          ]
        }
      }
    }
  }
}

我正在尝试阅读 LongitudeLatitude 以放置在地图中。

我该怎么做呢?它是从外部 API 中提取的

我试过了:

function on_page_ld() {
var parse_data = "api.example.com/api_name/?key=abcdefg12345"
var jsonData = JSON.parse();
for (var i = 1; i < jsonData.Routes.Route.RouteNo; i++) {
    var array = jsonData.Routes.Route.RouteNo[i];
    console.log(array);
  }
}

我得到:

VM4059:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0

【问题讨论】:

  • 我看到两个问题 1) var parse_data = "api.example.com/api_name/?key=abcdefg12345" - 你没有下载这个数据 2) var jsonData = JSON.parse(); - 在您的 JSON.parse 方法中,您需要传递您在上一行下载的数据
  • stackoverflow.com/questions/46613243/… 在 SO 上查看此帖子。看起来你正在传递 undefined ,这就是它在位置 0 解析 u 的原因

标签: javascript arrays json


【解决方案1】:

您可以使用 for-in 循环读取值

for (i in locations.length) {
  console.log(i + ") latitude :" + locations[i].latitude);
  console.log(i + ") longitude  :" + locations[i].longitude);
} 

【讨论】:

    【解决方案2】:
    async function on_page_ld(){
    // Fetching data from API
    const response = await fetch("api.example.com/api_name/?key=abcdefg12345")
    // Parsing JSON
    const data = await response.json()
    
    // Your array of latitudes and longitudes
    const locations = data.GetRouteSummaryForStopResult.Routes.Route.Trips.Trip
    
    // get all your latitudes and longitudes 
    for(i = 0; i < locations.length; i++){
     console.log(i + ") latitude :" + locations[i].latitude);
    console.log(i + ") longitude  :" + locations[i].longitude);
    }
    }
    

    【讨论】:

    • 谢谢!这对我帮助很大!
    猜你喜欢
    • 2019-10-24
    • 1970-01-01
    • 2018-01-24
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    相关资源
    最近更新 更多