访问JSON字符串时的TypeError

时间:2013-03-02 05:49:47

标签: javascript node.js casting websocket mongoose

我正在使用http://blockchain.info/api/api_websocket websocket api。

每个事务的json对象如下所示:

{
    "op": "utx",
    "x": {
        "hash": "f6c51463ea867ce58588fec2a77e9056046657b984fd28b1482912cdadd16374",
        "ver": 1,
        "vin_sz": 4,
        "vout_sz": 2,
        "lock_time": "Unavailable",
        "size": 796,
        "relayed_by": "209.15.238.250",
        "tx_index": 3187820,
        "time": 1331300839,
        "inputs": [
            {
                "prev_out": {
                    "value": 10000000,
                    "type": 0,
                    "addr": "12JSirdrJnQ8QWUaGZGiBPBYD19LxSPXho"
                }
            }
        ],
        "out": [
            {
                "value": 2800000000,
                "type": 0,
                "addr": "1FzzMfNt46cBeS41r6WHDH1iqxSyzmxChw"
            }
        ]
    }
}

我正在使用json.x.out [0] .addr访问“addr”变量,它在控制台中输出正常。

但是当我通过mongoose运行命令时:

Game.findOne({address:json.x.out[0].addr},function (err, game) {

导致以下错误:

TypeError: Cannot read property 'x' of undefined
    at Promise.<anonymous> (/Users/michael/Desktop/DugleyBit/app.js:176:25)
    at Promise.addBack (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/promise.js:133:8)
    at Promise.EventEmitter.emit (events.js:96:17)
    at Promise.emit (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/promise.js:66:38)
    at Promise.complete (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/promise.js:77:20)
    at Query.findOne (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/query.js:1607:15)
    at model.Document.init (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/document.js:227:11)
    at model.init (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/model.js:196:36)
    at Query.findOne (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/query.js:1605:12)
    at exports.tick (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/utils.js:404:16)

不是字符串吗?我该如何转换它?

由于

编辑:

请注意json格式正确:

var json = JSON.parse(message);

1 个答案:

答案 0 :(得分:0)

看起来json变量在您调用Game.findOne的范围内不可用。