Reputation: 1923
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..
Upvotes: 192
Views: 299020
Reputation: 1262
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'}
Upvotes: 8
Reputation: 24590
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());
Upvotes: 4
Reputation: 9406
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());
Upvotes: 357