我是这种格式的json:
[
{
"_id": {
"$oid": "560c079e1691682b4ff327ad"
},
"year": "2015",
"month": "9",
"day": "30",
"time": "17:02:17",
"problemDesc": "test",
"resolution": "test",
"IM": "test"
}
]
我尝试使用console.log(json[0].year)
访问年份,但接收undefined
。如何从这个json字符串中访问年份值?
答案 0 :(得分:5)
在JSFiddle中,json
中的值是一个字符串而不是JavaScript对象,您必须在尝试访问该值之前解析该字符串:
var json = JSON.parse('{"":[{"_id":{"$oid":"560c079e1691682b4ff327ad"},"year":"2015","month":"9","day":"30","time":"17:02:17","problemDesc":"test","resolution":"test","IM":"test"}]}');
console.log(json[''][0].year);
解析字符串后,需要使用键空字符串访问该对象:
json['']
与此键关联的值是一个数组,您需要第一个元素,因此:
json[''][0]
现在你可以获得这一年:
json[''][0].year
答案 1 :(得分:0)
你需要输入一个用于JSON的密钥,然后在解析之后通过密钥访问内部对象,因为它是一个用引号'
括起来的字符串var json = '{"key":[{"_id":{"$oid":"560c079e1691682b4ff327ad"},"year":"2015","month":"9","day":"30","time":"17:02:17","problemDesc":"test","resolution":"test","IM":"test"}]}'
console.log(JSON.parse(json)['key'][0].year);
答案 2 :(得分:0)
您需要使用json string
将json object
解析为JSON.parse
,然后在key name
''(empty string)
var jsonStr = '{"":[{"_id":{"$oid":"560c079e1691682b4ff327ad"},"year":"2015","month":"9","day":"30","time":"17:02:17","problemDesc":"test","resolution":"test","IM":"test"}]}';
var parseJson = JSON.parse(jsonStr);
alert(parseJson[''][0].year)