javascript - 使用 Javascript 显示嵌套的 JSON 数据

标签 javascript html json

下午好,

我正在尝试解析嵌套 json 对象中的数据。

例如:member.accuracy

目前,它返回的结果未定义

我的代码:

JSON(places.json):

{
"request_time": "2019-05-30T13:48:39+01:00",
"source": "Network Rail",
"acknowledgements": "Contains information of Network Rail Infrastructure Limited. License http://www.networkrail.co.uk/data-feeds/terms-and-conditions/",
"member": [
{
"type": "train_station",
"name": "London Euston",
"latitude": 51.528135,
"longitude": -0.133924,
"accuracy": 100,
"station_code": "EUS",
"tiploc_code": "EUSTON"
}
]
}

HTML:

   <html>  
    <head>  
    <meta content="text/html; charset=utf-8">  
    <title>AJAX JSON by Javatpoint</title>  
    <script type="application/javascript">  
    function load()  
    {  
       var url = "http://myurl.places.json?";
       var request;  

       if(window.XMLHttpRequest){    
        request=new XMLHttpRequest();//for Chrome, mozilla etc  
       }    
       else if(window.ActiveXObject){    
        request=new ActiveXObject("Microsoft.XMLHTTP");//for IE only  
       }    
       request.onreadystatechange  = function(){  
          if (request.readyState == 4  )  
          {  
            var jsonObj = JSON.parse(request.responseText);//JSON.parse() returns JSON object  
            document.getElementById("date").innerHTML =  jsonObj.request_time;  
            document.getElementById("time").innerHTML = jsonObj.member.accuracy;  
          }  
       }  
       request.open("GET", url, true);  
       request.send();  
    }  
    </script>  
    </head>  
    <body onload="load()">  

    Date: <span id="date"></span><br/>  
    Time: <span id="time"></span><br/>  


    </body>  
    </html>  

任何帮助将不胜感激!

谢谢

布拉德

最佳答案

正如您在 json 文件中看到的,成员属性保存一个数组,其中包含一个对象。为了获得准确性,您必须使用索引访问它:

var jsonObj = {
  "member": [{
    "type": "train_station",
    "name": "London Euston",
    "latitude": 51.528135,
    "longitude": -0.133924,
    "accuracy": 100,
    "station_code": "EUS",
    "tiploc_code": "EUSTON"
  }]
}
console.log(jsonObj.member[0].accuracy)

请注意,如果您从某种 API 获取此数据,则在将来的获取中此数组中可能存在多个对象,并且第一个元素(索引 0)可能会不是您要找的人。

关于javascript - 使用 Javascript 显示嵌套的 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56378707/

相关文章:

javascript - Angular:了解 DI 如何在动态加载的组件中工作

javascript - Express 将 URL 中的 “%2F” 替换为 “/”

jquery - 使用 CSS 和 JQuery 创建组织结构图

PHP 文件无法包含在 Wordpress 中使用 img

json - 使用自定义 MarshalJSON() 方法嵌入结构的惯用方法

javascript - 强制 DOM 在更改对工厂模型的 $scope 模型引用时进行渲染

javascript - 删除帐户前在 Firebase Auth 中验证用户密码

javascript - 如何在播放 HTML 5 视频(如 Youtube 广告)时添加图像/DIV?

javascript - JSON 对象作为键值对中的键

javascript - 我怎样才能摆脱这个错误以及为什么我无法进入该页面