levelDb put调用不能正确存储复杂的Json对象

问题描述 投票:0回答:1

我正在尝试使用LevelDb创建一个私有区块链,并且在levelDb中存储了一些存储复杂json对象的问题。

如果我尝试将简单的字符串或数字保存为值,它可以工作,但是当我尝试存储下面提到的复杂对象时,检索它时总是给我[对象对象]。请参阅下面的代码。

class Test {
    constructor() {
    this.level = require('level')

    // 1) Create our database, supply location and options.
    //    This will create or open the underlying store.
    this.db = this.level('my-db')

}

    test() {
        const self = this;
        // 2) Put a key & value
        self.db.put('name', {
            a: 123,
            b: 234,
            c: {
                d: 'dddddd'
            }
        }, function (err) {
            if (err) return console.log('Ooops!', err) // some kind of I/O error

            // 3) Fetch by key
            self.db.get('name', function (err, value) {
                if (err) return console.log('Ooops!', err) // likely the key was not found

                // Ta da!
                console.log('name=' + JSON.parse(JSON.stringify(value))); // Does not work shows [object Object]
                // console.log('name=' + JSON.stringify(value)); // Does not work shows [object Object]            
                // console.log('name=' + JSON.parse(value)); // Does not work shows ERROR SyntaxError: Unexpected token o in JSON at position 1
            })
        })
    }

}
blockchain leveldb
1个回答
0
投票

好吧,我通过使用像这样的put调用JSON.stringify(complexJsonObject)来修复它

test() {
    const self = this;
    // 2) Put a key & value
    self.db.put('name', JSON.stringify({
        a: 123,
        b: 234,
        c: {
            d: 'dddddd'
        }
    }), function (err) {
        if (err) return console.log('Ooops!', err) // some kind of I/O error

        // 3) Fetch by key
        self.db.get('name', function (err, value) {
            if (err) return console.log('Ooops!', err) // likely the key was not found

            // Ta da!
            console.log('name=' + JSON.parse(JSON.stringify(value))); // Does not work shows [object Object]
            // console.log('name=' + JSON.stringify(value)); // Does not work shows [object Object]            
            // console.log('name=' + JSON.parse(value)); // Does not work shows ERROR SyntaxError: Unexpected token o in JSON at position 1
        })
    })
}
© www.soinside.com 2019 - 2024. All rights reserved.