node.js 将 JSON 对象转换为 Buffer 并将 Buffer 转换为 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41951307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a JSON Object to Buffer and Buffer to JSON Object back
提问by Prasanth J
I have a JSON object and I'm converting it to a Bufferand doing some process here. Later I want to convert the same buffer data to convert to valid JSON object.
我有一个 JSON 对象,我正在将它转换为 aBuffer并在此处进行一些处理。后来我想将相同的缓冲区数据转换为有效的 JSON 对象。
I'm working on Node V6.9.1
我正在开发 Node V6.9.1
Below is the code I tried but I'm getting [object object]when I convert back to JSON and cannot open this object.
下面是我尝试过的代码,但是[object object]当我转换回 JSON 并且无法打开这个对象时,我得到了代码。
var obj = {
key:'value',
key:'value',
key:'value',
key:'value',
key:'value'
}
var buf = new Buffer.from(obj.toString());
console.log('Real Buffer ' + buf); //This prints --> Real Buffer <Buffer 5b 6f 62 6a 65 63 74>
var temp = buf.toString();
console.log('Buffer to String ' + buf); //This prints --> Buffer to String [object Object]
So I tried to print whole object using inspect way
所以我尝试使用检查方式打印整个对象
console.log('Full temp ' + require('util').inspect(buf, { depth: null })); //This prints --> '[object object]' [not printing the obj like declared above]
If i try to read it like an array
如果我尝试像数组一样读取它
console.log(buf[0]); // This prints --> [
I tried parsing also it throw SyntaxError: Unexpected token o in JSON at position 2
我也尝试解析它抛出 SyntaxError: Unexpected token o in JSON at position 2
I need to view it as real object like I created (I mean like declared above).
我需要像我创建的那样将它视为真实的对象(我的意思是像上面声明的那样)。
Please help..
请帮忙..
回答by Ebrahim Pasbani
You need to stringify the json, not calling toString
您需要对 json 进行字符串化,而不是调用 toString
var buf = Buffer.from(JSON.stringify(obj));
And for converting string to json obj :
并将字符串转换为 json obj :
var temp = JSON.parse(buf.toString());

