【问题标题】:How to override JSON.stringify method, NOT IN THE CUSTOM CALL, in the JSON class of the TypeScript project?如何在 TypeScript 项目的 JSON 类中覆盖 JSON.stringify 方法,而不是在自定义调用中?
【发布时间】:2020-04-15 15:15:59
【问题描述】:

我有 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 类。

【问题讨论】:

    标签: javascript json typescript object stringify


    【解决方案1】:

    考虑使用 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);
    };
    

    这应该可以解决您的 Maximum call stask exceeded 错误。

    【讨论】:

      【解决方案2】:

      你的方法不仅会删除循环引用,还会删除任何可见的对象,试试这个:

      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(decycle(yourJson),因为我不知道 yourJson 参数,只有这样:JSON.stringify = function(value) { return JSON .stringify(decycle(value)); },但我再次收到错误: RangeError: Maximum call stack size exceeded
      猜你喜欢
      • 2012-05-04
      • 1970-01-01
      • 2015-05-31
      • 1970-01-01
      • 2018-05-18
      • 2013-04-20
      • 1970-01-01
      • 1970-01-01
      • 2011-04-12
      相关资源
      最近更新 更多