JSON迭代对象并访问数据结果无法读取未定义的属性

时间:2014-07-31 17:13:54

标签: javascript 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
         }
    }       
}

1 个答案:

答案 0 :(得分:5)

不,这是你正在阅读“密钥”而不是变量的事实。您需要使用bracket notation, not dot notation

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

你不应该使用document.write。