开发者问题收集

无法读取 JSON - 无法读取未定义的属性

2018-04-14
11937

我已经在这个问题上挣扎了好一阵子了。当我尝试 console.log JSON 属性时,出现了以下错误:

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个回答

观察:

结果 看起来像一个 数组 ,而不是 对象

演示

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);

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

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);
Rohìt Jíndal
2018-04-16