簡體   English   中英

如何在 TypeScript 項目的 JSON 類中覆蓋 JSON.stringify 方法,而不是在自定義調用中?

[英]How to override JSON.stringify method, NOT IN THE CUSTOM CALL, in the JSON class of the TypeScript project?

我有 React Native 和 TypeScript 應用程序。 每周都會收到來自 Fabric 的錯誤:JSON.stringify 無法序列化循環結構。 沒有錯誤的情況。 我有很多使用 JSON.stringify 的第三方庫。 這意味着不可能在每個地方都放置自定義方法。 因此我無法捕捉到這個錯誤。 我的項目根目錄中有一個引導文件,我可以在其中覆蓋所有類。 我做了一個捕捉序列化循環結構的助手:

const getCircularReplacer = () => {
  const seen = new WeakSet();

  return (key: any, value: any) => {
    if (typeof value === 'object' && value !== null) {
      if (seen.has(value)) {
        return jsonStringify.circularReferenceReplacement;
      }
      seen.add(value);
    }

    return value;
  };
};

interface IJsonStringify {
  (value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
  circularReferenceReplacement?: any;
}

export const jsonStringify: IJsonStringify = (value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string => {
  return JSON.stringify(value, replacer || getCircularReplacer(), space);
};

當我嘗試在我的啟動文件中像這樣覆蓋我的 JSON.stringify 時:

JSON.stringify = (value: any) => {
  return jsonStringify(value);
};

我收到此錯誤:超出最大調用堆棧大小。 請有人寫出我做錯了什么或建議我如何根據我的助手覆蓋我的 JSON 類。

您的方法不僅會刪除循環引用,還會刪除任何可見的對象,請嘗試使用:

function decycle(obj, stack = []) {
    if (!obj || typeof obj !== 'object')
        return obj;

    if (stack.includes(obj))
        return null;

    let s = stack.concat([obj]);

    return Array.isArray(obj)
        ? obj.map(x => decycle(x, s))
        : Object.fromEntries(
            Object.entries(obj)
                .map(([k, v]) => [k, decycle(v, s)]));
}

你只是這樣稱呼它JSON.stringify(decycle(yourJson))

至於這個:

超出最大調用堆棧大小

您有一個遞歸函數,它在沒有退出條件的情況下調用自身。

考慮使用 json-stringify-safe

const {getSerialize} = require('json-stringify-safe');

const stringifyCore = JSON.stringify;
JSON.stringify = function (obj, replacer, spaces, cycleReplacer) {
    return stringifyCore(obj, getSerialize(replacer, cycleReplacer), spaces);
};

這應該可以解決您的最大調用 stask 超出錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM