Reading BigInt fields from json in node.js

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


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
  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?

>Solution :

your value is object

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

Leave a Reply