【发布时间】:2017-05-12 15:21:27
【问题描述】:
我正在构建一个 Web 应用程序,用于显示某个站点的下一班车。
它使用 TransportAPI,从那里我得到一个 JSON 文件:https://transportapi.com/v3/uk/bus/stop/450023470/live.json?app_id=221cce2f&app_key=d209929236fc97196775650c2bdb639e&group=route&limit=2&nextbuses=yes
JSON 在一个数组中,我无法访问 29 内的数据
{
"atcocode": "450023470",
"smscode": "45023470",
"request_time": "2017-05-11T11:57:51Z",
"name": "Headingley Campus",
"stop_name": "Headingley Campus",
"bearing": "N",
"indicator": "",
"locality": "Beckett Park, Leeds",
"departures": {
"29": [
{
"mode": "bus",
"line": "29",
"line_name": "29",
"direction": "Student Village",
"operator": "FL",
"date": "2017-05-11",
"expected_departure_date": "2017-05-11",
"aimed_departure_time": "13:05",
"expected_departure_time": "13:05",
"best_departure_estimate": "13:05",
"source": "NextBuses",
"dir": "inbound",
"id": "https:\/\/transportapi.com\/v3\/uk\/bus\/route\/FL\/29\/inbound\/450023470\/2017-05-11\/13:05\/timetable.json?app_id=221cce2f&app_key=d209929236fc97196775650c2bdb639e",
"operator_name": "First Leeds"
}
以下内容有效,但我并不总是知道 [29] 的值是什么。
alert(obj['departures'][29].length);
如何在不知道值的情况下获得长度?
完整代码如下
$.ajax({
type:"GET",
dataType: 'JSONP',
jsonpCallback: 'callback',
url: "https://transportapi.com/v3/uk/bus/stop/450023470/live.json?app_id=221cce2f&app_key=d209929236fc97196775650c2bdb639e&group=route&limit=2&nextbuses=yes",
success: function(data) {
var obj = jQuery.parseJSON(JSON.stringify(data));
alert(obj['departures'][29].length);
//$("body").append(JSON.stringify(data['departures'][29][0]['line_name']));
//alert(obj.departures.length);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
},
});
【问题讨论】:
-
只是一个命名的东西;您没有通过该警报获得对象的长度;你得到一个数组的长度。另外,当
data已经是一个对象时,不确定你为什么要这样做jQuery.parseJSON(JSON.stringify(data))...
标签: jquery arrays json ajax object