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

Jsonnode.jsBuffer

Json Problem Overview


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

Json Solutions


Solution 1 - Json

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

Solution 2 - Json

enter image description here

Kindly copy below snippet

const jsonObject = {
        "Name":'Ram',
        "Age":'28',
        "Dept":'IT'
      }
      const encodedJsonObject = Buffer.from(JSON.stringify(jsonObject)).toString('base64'); 
      console.log('--encodedJsonObject-->', encodedJsonObject)
      //Output     --encodedJsonObject--> eyJOYW1lIjoiUmFtIiwiQWdlIjoiMjgiLCJEZXB0IjoiSVQifQ==

      const decodedJsonObject = Buffer.from(encodedJsonObject, 'base64').toString('ascii'); 
      console.log('--decodedJsonObject-->', JSON.parse(decodedJsonObject))
      //Output     --decodedJsonObject--> {Name: 'Ram', Age: '28', Dept: 'IT'}

Solution 3 - Json

as @Ebrahim you have to use first JSON.stringify to convert the JSON to string, and then you can convert it to a Buffer. But it's little bit risky to use JSON.stringify since it can break your app in case of self refrencing or circular referncing:

   var y={}
   y.a=y
   JSON.stringify(y) // Uncaught TypeError: Converting circular structure to JSON

If you have such a risk, it better to use a safe stringify solution like this the npm module safe-json-stringify

And then you have to do:

// convert to buffer:
const stringify = require('safe-json-stringify');
var buf = Buffer.from(stringify(obj));

// convert from buffer:
var temp = JSON.parse(buf.toString());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPrasanth JView Question on Stackoverflow
Solution 1 - JsonEbrahim PasbaniView Answer on Stackoverflow
Solution 2 - JsonSantosh SinghView Answer on Stackoverflow
Solution 3 - JsonAminadav GlickshteinView Answer on Stackoverflow