JSON遍历对象和访问数据导致无法读取未定义的属性



我从一个网站解析json,并试图从它得到一些数据。但是,当迭代对象集合时,它会给我未定义的值。如果json格式不好,很遗憾,我无法更改它。

[
  {
    "startYear": 2014,
    "startMonth": 6,
    "startDay": 31,
    "endYear": 2014,
    "endMonth": 7,
    "endDay": 29,
    "selectedDate": "2014_7_8",
    "departureStation": "Manila",
    "arrivalStation": "Boracay (Caticlan)",
    "departureStationCode": "(MNL)",
    "arrivalStationCode": "(MPH)",
    "departureLabel": "DEPARTURE",
    "arrivalLabel": "RETURN",
    "dateMarketHash": {
      "date_0_2014_6_31": {
        "containerId": "date_0_2014_6_31",
        "fromLabel": "From",
        "currency": "PHP",
        "price": null,
        "formattedDate": "Thu, Jul 31, 2014",
        "year": "2014",
        "month": "6",
        "day": "31",
        "points": null,
        "pointsSuffix": "",
        "pointsLabelAppend": ""
      },
      "date_0_2014_7_1": {
        "containerId": "date_0_2014_7_1",
        "fromLabel": "From",
        "currency": "PHP",
        "price": 1929,
        "formattedDate": "Fri, Aug 01, 2014",
        "year": "2014",
        "month": "7",
        "day": "1",
        "points": 0,
        "pointsSuffix": "",
        "pointsLabelAppend": ""
      }
    }
  },
  {
    "startYear": 2014,
    "startMonth": 7,
    "startDay": 24,
    "endYear": 2014,
    "endMonth": 8,
    "endDay": 23,
    "selectedDate": "2014_8_8",
    "departureStation": "Boracay (Caticlan)",
    "arrivalStation": "Manila",
    "departureStationCode": "(MPH)",
    "arrivalStationCode": "(MNL)",
    "departureLabel": "DEPARTURE",
    "arrivalLabel": "RETURN",
    "dateMarketHash": {
      "date_1_2014_7_24": {
        "containerId": "date_1_2014_7_24",
        "fromLabel": "From",
        "currency": "PHP",
        "price": 3079,
        "formattedDate": "Sun, Aug 24, 2014",
        "year": "2014",
        "month": "7",
        "day": "24",
        "points": 0,
        "pointsSuffix": "",
        "pointsLabelAppend": ""
      },
      "date_1_2014_7_25": {
        "containerId": "date_1_2014_7_25",
        "fromLabel": "From",
        "currency": "PHP",
        "price": 3079,
        "formattedDate": "Mon, Aug 25, 2014",
        "year": "2014",
        "month": "7",
        "day": "25",
        "points": 0,
        "pointsSuffix": "",
        "pointsLabelAppend": ""
      }
    }
  }
]
我代码:

// Printing the value of 'day' from each 'dateMarketHash'
for (i = 0; i<json.length; i++)
{ 
    var current = json[i].dateMarketHash;
    for(var key in current){
         if (current.hasOwnProperty(key)) {
                document.write(current.key.day); // Cannot read property 'day' of undefined
         }
    }       
}

不,这是事实,你正在阅读"键",而不是变量。你需要使用括号符号,而不是点符号。

document.write(current[key].day);

你不应该使用document.write.

最新更新