我正在嘗試從這樣的檔案中讀取BigInt欄位:json
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
我究竟做錯了什么?
uj5u.com熱心網友回復:
你的價值是物件
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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/495394.html
標籤:javascript 节点.js json 大整数
