无法读取JSON - 无法读取未定义

时间:2018-04-14 20:37:21

标签: javascript json javascript-objects

我一直在努力解决这个问题。当我尝试console.log一个JSON proprty时,出现以下错误:

TypeError: Cannot read property 'timelineData' of undefined

这就是我的JSON文件:

{
  "default": {
    "timelineData": [{
      "time": "1359676800",
      "formattedTime": "Feb 1, 2013",
      "formattedAxisTime": "Feb 1, 2013",
      "value": [51],
      "hasData": [true],
      "formattedValue": ["51"]
    }, {
      "time": "1359763200",
      "formattedTime": "Feb 2, 2013",
      "formattedAxisTime": "Feb 2, 2013",
      "value": [53],
      "hasData": [true],
      "formattedValue": ["53"]
    }, {
      "time": "1359849600",
      "formattedTime": "Feb 3, 2013",
      "formattedAxisTime": "Feb 3, 2013",
      "value": [53],
      "hasData": [true],
      "formattedValue": ["53"]
    }],
    "averages": []
  }
}

这就是我要求数据的方式:

console.log(results.default.timelineData[0].time);

我不知道我做错了什么。也许我错误地解释了这个JSON对象?任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:1)

观察:

results看起来像array而不是object

<强>样本

&#13;
&#13;
var results = [{
	"default": {
		"timelineData": [{
			"time": "1359676800",
			"formattedTime": "Feb 1, 2013",
			"formattedAxisTime": "Feb 1, 2013",
			"value": [51],
			"hasData": [true],
			"formattedValue": ["51"]
		}, {
			"time": "1359763200",
			"formattedTime": "Feb 2, 2013",
			"formattedAxisTime": "Feb 2, 2013",
			"value": [53],
			"hasData": [true],
			"formattedValue": ["53"]
		}, {
			"time": "1359849600",
			"formattedTime": "Feb 3, 2013",
			"formattedAxisTime": "Feb 3, 2013",
			"value": [53],
			"hasData": [true],
			"formattedValue": ["53"]
		}],
		"averages": []
	}
}];

console.log(results.default.timelineData[0].time);
&#13;
&#13;
&#13;

因此,要访问time,您应该像这样使用:

&#13;
&#13;
var results = [{
	"default": {
		"timelineData": [{
			"time": "1359676800",
			"formattedTime": "Feb 1, 2013",
			"formattedAxisTime": "Feb 1, 2013",
			"value": [51],
			"hasData": [true],
			"formattedValue": ["51"]
		}, {
			"time": "1359763200",
			"formattedTime": "Feb 2, 2013",
			"formattedAxisTime": "Feb 2, 2013",
			"value": [53],
			"hasData": [true],
			"formattedValue": ["53"]
		}, {
			"time": "1359849600",
			"formattedTime": "Feb 3, 2013",
			"formattedAxisTime": "Feb 3, 2013",
			"value": [53],
			"hasData": [true],
			"formattedValue": ["53"]
		}],
		"averages": []
	}
}];

console.log(results[0].default.timelineData[0].time);
&#13;
&#13;
&#13;