我正在尝试使用LevelDb创建私有区块链,并在将复杂的json对象存储在levelDb中时遇到一些问题。
如果我尝试将简单的字符串或数字保存为值,那么它可以工作,但是当我尝试存储如下所述的复杂对象时,在检索它的同时总是给我[object Object]。请参见下面的代码。
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
})
})
}
}
答案 0 :(得分:0)
好吧,我通过将JSON.stringify(complexJsonObject)与这样的put调用一起使用来解决了这个问题
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
})
})
}