DEV Community

Cover image for How to convert a Buffer data to JSON in Node.js?
MELVIN GEORGE
MELVIN GEORGE

Posted on Originally published at melvingeorge.me

How to convert a Buffer data to JSON in Node.js?

Originally posted here!

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();
Enter fullscreen mode Exit fullscreen mode

For an example, let's say we have an array with some data like this,

// data
const data = [0x1, 0x2, 0x3, 0x4, 0x5];
Enter fullscreen mode Exit fullscreen mode

Now let's convert this data to buffer using the from() method in the Buffer class.

// data
const data = [0x1, 0x2, 0x3, 0x4, 0x5];

// for an example first let's convert
// this object to buffer
const buff = Buffer.from(data);
Enter fullscreen mode Exit fullscreen mode

Now let's convert this buffer to JSON using the toJSON() method in the buff object.

// data
const data = {
  name: "John Doe",
  age: 23,
};

// for an example first let's convert
// this object to buffer
const buff = Buffer.from(data);

// buffer to JSON
// using the toJSON() method
const json = buff.toJSON();

console.log(json);
/*
{ type: 'Buffer', data: [ 1, 2, 3, 4, 5 ] }
*/
Enter fullscreen mode Exit fullscreen mode
  • The actual data will be in a property called data and the type of data is in a property called type in the json object.

See this example live in repl.it.

Feel free to share if you found this useful 😃.


Top comments (2)

Collapse
 
fleker profile image
Nick •

This was the first result and it perfectly answered my question. Cheers!

Collapse
 
leejinz profile image
Lee Jinz •

Thank you so much. And I have a question How to convert from { type: 'Buffer', data: [ 1, 2, 3, 4, 5 ] } to object same as data = {name: "John Doe", age: 23,};