[英]Display nested JSON data using Javascript
Afternoon all, 下午都
I'm trying to parse data from a nested json object. 我正在尝试从嵌套的json对象解析数据。
For example: member.accuracy
例如:
member.accuracy
Currently, it's returning the result undefined
. 目前,它正在返回结果
undefined
。
My code: 我的代码:
JSON (places.json): 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:
<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>
Any help would be much appreciated! 任何帮助将非常感激!
Thanks, 谢谢,
Brad 布拉德
As you can see in the json file, the member property holds an array, containing one object. 正如您在json文件中看到的那样,member属性包含一个数组,其中包含一个对象。 To get
accuracy
, you must access it with an index: 为了获得
accuracy
,您必须使用索引来访问它:
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)
Be aware that if you're fetching this data from some sort of API, there may be more than one object present in this array in future fetches, and the first element (index 0
) may not be the one you're looking for. 请注意,如果您要通过某种API来获取此数据,则在以后的获取中此数组中可能存在多个对象,并且第一个元素(索引
0
)可能不是您要查找的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.