TypeError: BigInt value can't be serialized in JSON

當在 JSON.stringify 中遇到 BigInt 值,且未提供自定義序列化方法時,會發生 JavaScript 異常“BigInt 值不能在 JSON 中序列化”。

訊息

TypeError: Do not know how to serialize a BigInt (V8-based)
TypeError: BigInt value can't be serialized in JSON (Firefox)
TypeError: JSON.stringify cannot serialize BigInt. (Safari)

錯誤型別

TypeError

哪裡出錯了?

你正在嘗試使用 JSON.stringify 序列化 BigInt 值,但它預設不支援 BigInt 值。有時,JSON 字串化會在庫中隱式發生,作為資料序列化的一部分。例如,將資料傳送到伺服器、將其儲存在外部儲存中或線上程之間傳輸都需要序列化,這通常使用 JSON 完成。

有幾種處理方法

  • 如果你可以更改資料來源,請避免使用 BigInt 值,並先將其轉換為數字(這可能會導致大數字的精度丟失)。
  • 如果你可以更改字串化過程,請向 JSON.stringify 傳遞一個替換函式,該函式將 BigInt 值轉換為字串或數字。
  • 你還可以全域性提供一個 BigInt.prototype.toJSON 方法,該方法在 BigInt 值被字串化時呼叫。

有關各種權衡的更多資訊,請參閱 BigInt 參考

示例

提供自定義序列化方法

預設情況下,BigInt 值不能在 JSON 中序列化

js
const data = { a: 1n };
JSON.stringify(data);
// TypeError: BigInt value can't be serialized in JSON

假設你希望 JSON 包含一個數字值,以下是一些可行的方法

  • 在字串化之前將 BigInt 轉換為數字

    js
    const data = { a: 1n };
    JSON.stringify({ ...data, a: Number(data.a) });
    // '{"a":1}'
    
  • 提供一個替換函式,將 BigInt 值轉換為數字或 原始 JSON 物件

    js
    const data = { a: 1n };
    JSON.stringify(data, (key, value) =>
      typeof value === "bigint" ? Number(value) : value,
    );
    // '{"a":1}'
    
    js
    const data = { a: 1n };
    JSON.stringify(data, (key, value) =>
      typeof value === "bigint" ? JSON.rawJSON(value.toString()) : value,
    );
    // '{"a":1}'
    
  • 提供一個 BigInt.prototype.toJSON 方法,該方法在 BigInt 值被字串化時呼叫

    js
    BigInt.prototype.toJSON = function () {
      return Number(this);
    };
    const data = { a: 1n };
    JSON.stringify(data);
    // '{"a":1}'
    
    js
    BigInt.prototype.toJSON = function () {
      return JSON.rawJSON(this.toString());
    };
    const data = { a: 1n };
    JSON.stringify(data);
    // '{"a":1}'
    

另見