Does JSON.parse() accepts a Buffer as argument?

Viewed 1215

The following code works in Node.js v14.16.0. However, I can't find any documentation indicating that JSON.parse() accepts a Buffer as the argument. Is this expected behavior—yet not documented—or perhaps I'm doing something wrong?

const fs = require('fs');
const dataPayload = fs.readFileSync('data.json'); // a buffer
const data = JSON.parse(dataPayload);

console.log(data); // { name: 'Jane', age: 24 } -> an object

Contents of data.json:

{
  "name": "Jane",
  "age": 24
}

The spec does not mention anything related to this.

1 Answers

It ends up converting the Buffer to a string and that is described in the ECMAScript spec when you pass an Object to JSON.parse(text [,reviver]).

The ECMAScript spec for JSON.parse() contains this first step:

Let JText be ToString(text).

So, the very first step is to take the first argument you pass to JSON.parse(text) and convert it to a string if it's not already. If you want to see how ToString(text) works, that is described here in the spec. In this case, a Buffer would be an Object so it would follow that path which calls the internal ToPrimitive() with a hint of string as the type and then calling the internal ToString() on that.


Here's a little example that runs in a snippet to show that it's using the .toString() method on the object:

let data = {
    toString() {
         console.log(`".toString()" method called`);
         return "[1,2,3]";    // return some JSON
    }
};

let test = JSON.parse(data);

console.log(`Is this an array: ${Array.isArray(test)}`);
console.log(`Array of length: ${test.length}`);
console.log(test);

Related