Convert a JSON Object to Buffer and Buffer to JSON Object back

Prasanth J picture Prasanth J · Jan 31, 2017 · Viewed 112.3k times · Source

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..

Answer

Ebrahim Pasbani picture Ebrahim Pasbani · Jan 31, 2017

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());