最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Does JSON.parse() accepts a Buffer as argument? - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Apr 7, 2021 at 20:58 Mauro P.Mauro P. 1652 silver badges10 bronze badges 2
  • 5 Afaik, if the passed object isn't a string, JSON.parse() calls .toString() on it first. A mon beginner's error for instance is passing objects to JSON.parse(), this will lead to JSON.parse plaining about an unexpected character o because it tries to parse "[object Object]" – user5734311 Commented Apr 7, 2021 at 21:00
  • 1 Same as dataPayload.toString() – Bergi Commented Apr 7, 2021 at 21:08
Add a ment  | 

1 Answer 1

Reset to default 8

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);

发布评论

评论列表(0)

  1. 暂无评论