How to use the Node.js Buffer.toJSON() method

The Buffer.toJSON() method returns the buffer object as JSONJavaScript Object Notation object.

JSON:

  • Is a lightweight data-interchange format.
  • Is easy for humans to read.
  • Contains key/value pairs.

Example

{
"name" : "John",
"age" : 30
}
  • In the example above, name and age are keys and John and 30 are values, respectively.
  • Key:Value pairs are separated by a comma ,.

Syntax

buffer.toJSON()

Parameters

This method does not take any parameters.

Return value

The toJSON() method returns the JSON format of the buffer object on which it is called. Check out the following examples to understand how it works.

Example 1

In the following example:

  • We construct the buffer object buf from the fill as abcd.
  • In line 4 we convert the buffer object buf into JSON format with the buf.toJSON() method.
  • Output contains type and data. Here type is Buffer and data is the data present in the buffer object buf.
const buf = Buffer.from('abcd')
//Note: tojson() or toJson() will throw error, mention exact case.
console.log(buf.toJSON())

Example 2

The following code snippet is the same as Example 1, except that we pass base64 as encoding format to encode the fill abcd.

const buf = Buffer.from('abcd','base64')
console.log(buf.toJSON())

Free Resources