The toJSON() method returns a JSON object based on the Buffer object.
To convert a Buffer to JSON , you can use the toJSON() method in the Buffer instance. // convert buff object to json const json = buff. toJSON();
The Buffer. toJSON() method returns the buffer in JSON format.
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());
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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With