Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Which code converts a buffer buffer to JSON object?

The toJSON() method returns a JSON object based on the Buffer object.

How do you convert an instance of the Buffer class to a JSON 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();

What does Buf toJSON () method return in node JS?

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

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