Tue Apr 1
  :  :  

BSON

Given a JavaScript object with bigint values, then JSON.stringify and JSON.parse stops working. This is because the JSON functions does not support bigint values natively.

To get around this in a quick and easy way, the code below can be used. What the code does is that it converts bigint values into strings with a n appended at the end. Hence, the edge case where it breaks is if a string has leading digits and ends with the letter n, and would instead be interpreted as a bigint instead of a string.

export default class BSON {
  static stringify(value: string, space?: string | number) {
    return JSON.stringify(value, replacer, space);
  }

  static parse(text: string) {
    return JSON.parse(text, reviver);
  }
}

function replacer(key: string, value: any) {
  if (typeof value === "bigint") {
    return value.toString() + 'n';
  }
  return value;
}

function reviver(key: string, value: any) {
  if (typeof value === 'string' && /^d+n$/.test(value)) {
    return BigInt(value.slice(0, -1));
  }
  return value;
}