Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading