193

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

2

3 Answers 3

356

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());
Sign up to request clarification or add additional context in comments.

6 Comments

This will not work if is there's another buffer field in obj
actually, toString is not needed here. groups.google.com/forum/#!topic/nodejs/hybuh7DbQkM
for me, it worked when I took away the JSON.stringify and put the object directly inside the parameters, like so: var buf = Buffer.from({ key:'value', key:'value', key:'value', key:'value', key:'value' });
@Dzenly while toString is technically not needed, it should be used. Reading the page you linked, it states that the buffer is converted to a string (using Buffer.toString) using utf8 encoding, and while normally this is not an issue, if the buffer was created in some other encoding, you will get garbage. So really, for things like this, it should be fine, but for a lot of other scenarios (where you have little to no control over things passed in), knowing and respecting the encoding is a must
Good point @werlious, plus typescript doesn't allow JSON.parse(buffer)
|
8

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'}

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.