English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer & URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File (FS)

NodeJS Others

Node.js Convert JSON to Buffer

Node.js – To convert JSON to Buffer, first convert the JSON object to a string using JSON.stringify(jsonObj), and then use the Buffer.from(jsonStr) method to read the JSON string into the buffer. Example
Here is an example demonstrating how to convert a 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 into buffer
const buf = Buffer.from(jsonStr);
 
console.log(buf.length);

Output Result

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

In the next Node.js tutorial, we will learn how to convert Buffer data to JSON objects.