下午,
我正在尝试从嵌套的json对象解析数据。
例如:member.accuracy
当前,它正在返回结果undefined
。
我的代码:
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>
任何帮助将不胜感激!
谢谢
布拉德
答案 0 :(得分:3)
正如您在json文件中看到的那样,member属性包含一个数组,其中包含一个对象。要获取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)
请注意,如果您要通过某种API来获取此数据,则在以后的提取中此数组中可能存在多个对象,而第一个元素(索引0
)可能不是您正在寻找的那个。