使用nodeJs在Json中解析数组

时间:2018-02-24 15:37:33

标签: arrays json node.js

这是我的json:

{

    "xuid":****************,
    "state":"Online",
    "devices":[
        {
            "type":"XboxOne",
            "titles":[
                {
                    "id":750323071,
                    "name":"Accueil",
                    "placement":"Background",
                    "state":"Active",
                    "lastModified":"2018-02-23T17:09:38.4018406Z"
                },
                {
                    "id":1145574011,
                    "activity":{
                        "richPresence":"Dans un salon priv\u00e9"
                    },
                    "name":"Titanfall\u2122 2",
                    "placement":"Full",
                    "state":"Active",
                    "lastModified":"2018-02-23T17:09:38.4018406Z"
                }
            ]
        }
    ]

}

我想恢复价值:devices->titles->1->activity->richPresence
这是我的nodeJs代码:

function (error, response, body) {
    if (!error && response.statusCode === 200) {
        var xbJson = JSON.parse(body);          
        console.log(xbJson.devices.titles[1]['name'])
    }
}

我的错误:

TypeError: Cannot read property '1' of undefined
    at Request._callback (/home/atmoner/Bureau/xboxlive/test.js:16:40)
    at Request.self.callback (/home/atmoner/Bureau/xboxlive/node_modules/request/request.js:186:22)
    at emitTwo (events.js:125:13)
    at Request.emit (events.js:213:7)
    at Request.<anonymous> (/home/atmoner/Bureau/xboxlive/node_modules/request/request.js:1163:10)
    at emitOne (events.js:115:13)
    at Request.emit (events.js:210:7)
    at IncomingMessage.<anonymous> (/home/atmoner/Bureau/xboxlive/node_modules/request/request.js:1085:12)
    at Object.onceWrapper (events.js:312:19)
    at emitNone (events.js:110:20)

我猜这个问题来自json中的数组,我无法继续前进 听起来很简单,但我需要一些帮助。 谢谢!...

1 个答案:

答案 0 :(得分:1)

试试这个:

console.log(xbJson.devices[0].titles[1]['name'])