无法访问js属性

时间:2015-10-05 13:34:55

标签: javascript json

我是这种格式的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字符串中访问年份值?

小提琴:

http://jsfiddle.net/b8dggkof/

3 个答案:

答案 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 stringjson 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)