Convert a JSON Object to Buffer and Buffer to JSON

2019-03-14 09:41发布

问题:

I have a JSON object and i'm converting it to a Buffer and doing some process here. Later i want to convert the same buffer data to convert to valid JSON object.

I'm working on 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.

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

I need to view it as real object like i created [i mean like declared above].

Please help..

回答1:

You need to stringify the json, not calling toString

var buf = Buffer.from(JSON.stringify(obj));

And for converting string to json obj :

var temp = JSON.parse(buf.toString());