从Node.js中阅读JSON的Bigint字段

发布于 2025-02-10 06:27:13 字数 1227 浏览 1 评论 0 原文

我正在尝试从 json 文件中读取 bigint 字段:

const fs = require("fs");

function reviver(key, value) {
  return BigInt(value);
}

let rawdata = fs.readFileSync("input.json");
let numbers = JSON.parse(rawdata, reviver);

console.log(numbers);

我的输入json文件看起来像这样:

[
    {"number": 19819, "divisor":  34},
    {"number":   888, "divisor":  19},
    {"number": 55555, "divisor": 126}
]

这是我遇到的错误:

$ node div.js
/home/oren/div.js:4
  return BigInt(value);
         ^

SyntaxError: Cannot convert [object Object] to a BigInt
    at BigInt (<anonymous>)
    at Array.reviver (/home/oren/div.js:4:10)
    at JSON.parse (<anonymous>)
    at Object.<anonymous> (/home/oren/div.js:8:20)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

我在做什么错?

I am trying to read BigInt fields from a json file like this:

const fs = require("fs");

function reviver(key, value) {
  return BigInt(value);
}

let rawdata = fs.readFileSync("input.json");
let numbers = JSON.parse(rawdata, reviver);

console.log(numbers);

My input json file looks like this:

[
    {"number": 19819, "divisor":  34},
    {"number":   888, "divisor":  19},
    {"number": 55555, "divisor": 126}
]

Here is the error that I get:

$ node div.js
/home/oren/div.js:4
  return BigInt(value);
         ^

SyntaxError: Cannot convert [object Object] to a BigInt
    at BigInt (<anonymous>)
    at Array.reviver (/home/oren/div.js:4:10)
    at JSON.parse (<anonymous>)
    at Object.<anonymous> (/home/oren/div.js:8:20)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

What am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光暖心i 2025-02-17 06:27:13

您的值是对象

function reviver(key, value) {
  return typeof value === 'number' ? BigInt(value) : value;
}

your value is object

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter

function reviver(key, value) {
  return typeof value === 'number' ? BigInt(value) : value;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文