Published on

How to Serialize BigInt Values in JSON

Authors
  • Name
    Twitter

When working with Solana programs and blockchain data, you'll frequently encounter large numbers that need to be represented as BigInts. However, if you try to save transaction data or account balances to a JSON file using JSON.stringify(), you may run into the frustrating error: "TypeError: Do not know how to serialize a BigInt".

This is a common issue since JavaScript's JSON serializer doesn't natively support the BigInt type that's often used for lamports, token amounts, and other blockchain values. Fortunately, there's a simple solution that allows you to serialize your BigInt data by adding a custom conversion method. Here's the code you'll need:

// Allow BigInts to be parsed into a JSON file
BigInt.prototype["toJSON"] = function () {
  return this.toString();
};