Node.js – Convert JSON to Buffer

To convert JSON to Buffer, first convert JSON object to string JSON.stringify(jsonObj); , then use Buffer.from(jsonStr)  method to read the JSON string to a buffer.

In this tutorial, we will convert JSON to Buffer using JSON.stringify() and give some examples on the same.

Example 1 – JSON to Buffer

In this example, we will take a JSON string, convert it to JSON Object, and then convert this JSON Object to a Buffer.

convert-json-to-buffer.js

const msg = '{"name":"John", "age":"22"}';
var jsonObj = JSON.parse(msg);

// convert JSON object to String
var jsonStr = JSON.stringify(jsonObj);

// read json string to Buffer
const buf = Buffer.from(jsonStr);

console.log(buf.length);

Output

$ node convert-json-to-buffer.js 
26
ADVERTISEMENT

Conclusion

In this Node.js Tutorial, we have learnt to convert JSON String to Buffer. In our next tutorial, we shall learn to convert Buffer data to a JSON object.