我正在構建一個web應用程序,顯示來自某個站點的下一班車。獲取json中的對象的長度
它使用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);
},
});
只是一個命名的事;你沒有得到具有該警報的對象的長度;你會得到一個數組的長度。此外,不知道爲什麼你在做'jQuery.parseJSON(JSON.stringify(data))',當'data'已經是一個對象... –