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

7

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


Tiugo image

Fast, Lean, and Fully Extensible

CKEditor 5 is built for developers who value flexibility and speed. Pick the features that matter, drop the ones that don’t and enjoy a high-performance WYSIWYG that fits into your workflow

Start now

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,};

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay