As we know the BigInt type is availble in JavaScript as a data type able to represent any arbitrary large integer number, which is a good supplement when a value exceeds what number could represent. However, when working with applications where you need exchange data with JSON format, the bigint values become a problem because JSON does not know how to serialize bigint values by default, in such cases, one solution is to convert the bigint into string as this post shows.

The problem

> const obj = {
... name: 'andy',
... age: 36,
... money: 1000000000000000000000000n
... }
undefined
> JSON.stringify(obj)
Uncaught TypeError: Do not know how to serialize a BigInt
    at JSON.stringify (<anonymous>)

The solution

  • Monkey patch BigInt:
> BigInt.prototype.toJSON = function () {
... return this.toString();
... }
[Function (anonymous)]
> JSON.stringify(obj)
'{"name":"andy","age":36,"money":"1000000000000000000000000"}'
  • Handle specific bigint field:
const obj = {
  name: 'andy',
  age: 36,
  money: 1000000000000000000000000n
};
// stringify
function replacer(key, value) {
  if (key === 'money') {
    return value.toString();
  }
  return value;
}
const stringified = JSON.stringify(obj, replacer);

// parsing
function reviver(key, value) {
  if (key === 'money') {
    return BigInt(value);
  }
  return value;
}

const payload = '{"name":"andy","age":36,"money":"1000000000000000000000000"}';
const parsed = JSON.parse(payload, reviver);
  • Handle any value that is bigint:
JSON.stringify(this, (key, value) =>
  typeof value === 'bigint'
      ? value.toString()
      : value // return everything else unchanged
);

References

TOP▲
Post tagged with: js, javascript, json