How to use the Node.js Buffer.toJSON() method
The Buffer.toJSON() method returns the buffer object as
JSON:
- Is a lightweight data-interchange format.
- Is easy for humans to read.
- Contains
key/valuepairs.
Example
{
"name" : "John",
"age" : 30
}
- In the example above,
nameandageare keys andJohnand30are values, respectively. Key:Valuepairs 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
buffrom the fill asabcd. - In line
4we convert the buffer objectbufintoJSONformat with thebuf.toJSON()method. - Output contains
typeanddata. HeretypeisBufferanddatais the data present in the buffer objectbuf.
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())