9 个JSON.stringify的秘密大多数开发人员却不知道

news2025/2/23 16:49:49

作为前端开发工程师,你一定用过JSON.stringify,但你知道它的全部秘密吗?

很久以前,我因此在工作中犯下了无法挽回的错误。如果我早点知道,就不会发生这样的悲剧。

理解 JSON.stringify

基本上,JSON.stringify 将对象转换为 JSON 字符串。同时,JSON.stringify 有如下规则。

1.undefined、Function 和 Symbol 不是有效的 JSON 值。

如果在转换过程中遇到任何此类值,它们要么被省略(当在对象中找到时),要么更改为 null(当在数组中找到时)。

当传入像 JSON.stringify(function() {}) 或 JSON.stringify(undefined) 这样的“纯”值时,JSON.stringify() 可以返回 undefined。

2.Boolean、Number、String对象在字符串化过程中被转换为对应的原始值,符合传统的转换语义。

3.所有以符号为键的属性将被完全忽略,即使在使用替换函数时也是如此。

4.数字 Infinity 和 NaN,以及值 null,都被认为是 null。

5.如果该值有一个 toJSON() 方法,它负责定义哪些数据将被序列化。

6.Date实例通过返回字符串实现toJSON()函数(同date.toISOString())。因此,它们被视为字符串。

7.在包含循环引用的对象上执行此方法会抛出错误。

8.所有其他对象实例(包括 Map、Set、WeakMap 和 WeakSet)将只序列化它们的可枚举属性。

9.尝试转换BigInt类型的值时抛出错误。

自己实现 JSON.stringify

理解功能的最好方法是自己去实现它。下面我写了一个简单的函数来模拟JSON.stringify。

const jsonstringify = (data) => {
  // Check if an object has a circular reference
  const isCyclic = (obj) => {
  // Use the Set data type to store detected objects
  let stackSet = new Set()
  let detected = false

  const detect = (obj) => {
    // If it is not an object type, you can skip it directly
    if (obj && typeof obj != 'object') {
      return
    }
    // When the object to be checked already exists in the stackSet, it means that there is a circular reference
    if (stackSet.has(obj)) {
      return detected = true
    }
    // Save the current obj as a stackSet
    stackSet.add(obj)

    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        detect(obj[key])
      }
    }
    // After the level detection is completed, delete the current object to prevent misjudgment
    /*
      For example:
      an object's attribute points to the same reference. 
      If it is not deleted, it will be regarded as a circular reference
      let tempObj = {
        name: 'fatfish'
      }
      let obj4 = {
        obj1: tempObj,
        obj2: tempObj
      }
    */
    stackSet.delete(obj)
  }

  detect(obj)

  return detected
}

  // 7#:
  // Executing this method on an object that contains a circular reference throws an error.

  if (isCyclic(data)) {
    throw new TypeError('Converting circular structure to JSON')
  }

  // 9#: An error is thrown when trying to convert a value of type BigInt
  // An error is thrown when trying to convert a value of type bigint
  if (typeof data === 'bigint') {
    throw new TypeError('Do not know how to serialize a BigInt')
  }

  const type = typeof data
  const commonKeys1 = ['undefined', 'function', 'symbol']
  const getType = (s) => {
    return Object.prototype.toString.call(s).replace(/\[object (.*?)\]/, '$1').toLowerCase()
  }

  // not an object
  if (type !== 'object' || data === null) {
    let result = data
    // 4#:The numbers Infinity and NaN, as well as the value null, are all considered null.
    if ([NaN, Infinity, null].includes(data)) {
      result = 'null'
      // 1#:undefined, Function, and Symbol are not valid JSON values. 
      // If any such values are encountered during conversion they are either omitted (when found in an object) or changed to null (when found in an array). 
      // JSON.stringify() can return undefined when passing in "pure" values like JSON.stringify(function() {}) or JSON.stringify(undefined).
    } else if (commonKeys1.includes(type)) {
      return undefined
    } else if (type === 'string') {
      result = '"' + data + '"'
    }

    return String(result)
  } else if (type === 'object') {
    // 5#: If the value has a toJSON() method, it's responsible to define what data will be serialized.
    // 6#: The instances of Date implement the toJSON() function by returning a string (the same as date.toISOString()). 
    // Thus, they are treated as strings.
    if (typeof data.toJSON === 'function') {
      return jsonstringify(data.toJSON())
    } else if (Array.isArray(data)) {
      let result = data.map((it) => {
        // 1#: If any such values are encountered during conversion they are either omitted (when found in an object) or changed to null (when found in an array). 
        return commonKeys1.includes(typeof it) ? 'null' : jsonstringify(it)
      })

      return `[${result}]`.replace(/'/g, '"')
    } else {
      // 2#:Boolean, Number, and String objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics.
      if (['boolean', 'number'].includes(getType(data))) {
        return String(data)
      } else if (getType(data) === 'string') {
        return '"' + data + '"'
      } else {
        let result = []
        // 8#: All the other Object instances (including Map, Set, WeakMap, and WeakSet) will have only their enumerable properties serialized.
        Object.keys(data).forEach((key) => {
          // 3#: All Symbol-keyed properties will be completely ignored, even when using the replacer function.
          if (typeof key !== 'symbol') {
            const value = data[key]
            // 1#: undefined, Function, and Symbol are not valid JSON values.
            if (!commonKeys1.includes(typeof value)) {
              result.push(`"${key}":${jsonstringify(value)}`)
            }
          }
        })

        return `{${result}}`.replace(/'/, '"')
      }
    }
  }
}

还有一个测试

// 1. Test basic features
console.log(jsonstringify(undefined)) // undefined 
console.log(jsonstringify(() => { })) // undefined
console.log(jsonstringify(Symbol('fatfish'))) // undefined
console.log(jsonstringify((NaN))) // null
console.log(jsonstringify((Infinity))) // null
console.log(jsonstringify((null))) // null
console.log(jsonstringify({
  name: 'fatfish',
  toJSON() {
    return {
      name: 'fatfish2',
      sex: 'boy'
    }
  }
}))
// {"name":"fatfish2","sex":"boy"}

// 2. Compare with native JSON.stringify
console.log(jsonstringify(null) === JSON.stringify(null));
// true
console.log(jsonstringify(undefined) === JSON.stringify(undefined));
// true
console.log(jsonstringify(false) === JSON.stringify(false));
// true
console.log(jsonstringify(NaN) === JSON.stringify(NaN));
// true
console.log(jsonstringify(Infinity) === JSON.stringify(Infinity));
// true
let str = "fatfish";
console.log(jsonstringify(str) === JSON.stringify(str));
// true
let reg = new RegExp("\w");
console.log(jsonstringify(reg) === JSON.stringify(reg));
// true
let date = new Date();
console.log(jsonstringify(date) === JSON.stringify(date));
// true
let sym = Symbol('fatfish');
console.log(jsonstringify(sym) === JSON.stringify(sym));
// true
let array = [1, 2, 3];
console.log(jsonstringify(array) === JSON.stringify(array));
// true
let obj = {
  name: 'fatfish',
  age: 18,
  attr: ['coding', 123],
  date: new Date(),
  uni: Symbol(2),
  sayHi: function () {
    console.log("hello world")
  },
  info: {
    age: 16,
    intro: {
      money: undefined,
      job: null
    }
  },
  pakingObj: {
    boolean: new Boolean(false),
    string: new String('fatfish'),
    number: new Number(1),
  }
}
console.log(jsonstringify(obj) === JSON.stringify(obj)) 
// true
console.log((jsonstringify(obj)))
// {"name":"fatfish","age":18,"attr":["coding",123],"date":"2021-10-06T14:59:58.306Z","info":{"age":16,"intro":{"job":null}},"pakingObj":{"boolean":false,"string":"fatfish","number":1}}
console.log(JSON.stringify(obj))
// {"name":"fatfish","age":18,"attr":["coding",123],"date":"2021-10-06T14:59:58.306Z","info":{"age":16,"intro":{"job":null}},"pakingObj":{"boolean":false,"string":"fatfish","number":1}}

// 3. Test traversable objects
let enumerableObj = {}

Object.defineProperties(enumerableObj, {
  name: {
    value: 'fatfish',
    enumerable: true
  },
  sex: {
    value: 'boy',
    enumerable: false
  },
})

console.log(jsonstringify(enumerableObj))
// {"name":"fatfish"}

// 4. Testing circular references and Bigint

let obj1 = { a: 'aa' }
let obj2 = { name: 'fatfish', a: obj1, b: obj1 }
obj2.obj = obj2

console.log(jsonstringify(obj2))
// TypeError: Converting circular structure to JSON
console.log(jsonStringify(BigInt(1)))
// TypeError: Do not know how to serialize a BigInt

如有需要前端资料或者毕设源码点击下载资料 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/416496.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

神经网络辐射场NeRF、实时NeRF Baking、有向距离场SDF、占用网络Occupancy、NeRF 自动驾驶

1 NeRF原理2 NeRF加速PlenoxelsKiloNeRFInstant NGPTensoRF3 SDF NeRF4 Occupancy NeRF5 NeRF应用简介常见应用实际应用的挑战6 NeRF自动驾驶1 NeRF原理 NeRF (Neural Radiance Fields,神经辐射场) 是2020年ECCV会议上的Best Paper,其将隐式表达推上了…

安卓玩机搞机----移植第三方rom修复 第三方GSI系统修复bug综合解析【一】

很多朋友热衷与刷写第三方非当前机型官方系统的rom。和刷写第三方gsi等等。例如 米系列机型刷写Flyme 一加机型刷写miui oppo刷写gsi等等。 很多友友也会尝试自己移植第三方rom。但此类操作最大的问题在于修复可以开机后的bug,今天的教程综合说明下这类修复思路…

STM32F103RCT6

STM32F103RCT6是一款由STMicroelectronics公司生产的基于ARM Cortex-M3内核的32位微控制器。 它具有高性能、低功耗和广泛的应用领域。 包括ADC(模数转换器) DAC(数字模拟转换器) TIM(定时器) USART&#x…

Python 中 SyntaxError: ‘yield‘ outside function 错误

当我们在函数外部使用 yield 关键字时,会出现 Python “SyntaxError: ‘yield’ outside function”。 要解决该错误,如果我们需要对每个元素执行一些运算符,请使用列表理解,或者缩进函数内部使用 yield 的代码。 下面是一个产生…

Maven(四):Maven的使用(中)

Maven(四):Maven的使用(中)前言一、实验四:创建 Maven 版的 Web 工程1、说明2、操作3、生成的pom.xml4、生成的Web工程的目录结构5、创建 Servlet5.1 在 main 目录下创建 java 目录5.2 在 java 目录下创建 …

【从零开始学Skynet】实战篇《球球大作战》(六):gateway代码设计(中)

1、编码和解码 我们来实现两个辅助方法str_unpack和str_pack,用于消息的解码和编码。 (1)str_unpack代码 local str_unpack function(msgstr)local msg {}while true dolocal arg, rest string.match( msgstr, "(.-),(.*)")if…

TCP/IP协议及配置

文章目录一、TCP/IP概述1. TCP/IP协议族2. 主机与主机之间通信的三个要素二、什么是IP地址1. 用来标识一个网络节点的互联网地址(如同电话的号码)2. IPv4地址组成三、IP地址分类1. 常用的IP地址2. 组播及科研专用四、IP地址分类(续&#xff0…

wsl下安装cuda各种踩坑记录.assets

执行nvcc -V, cuda版本位11.5 删除cuda sudo apt-get --purge remove "*cublas*" "*cufft*" "*curand*" \"*cusolver*" "*cusparse*" "*npp*" "*nvjpeg*" "cuda*" "nsight*"选择对…

打造自己特色远程桌面:SmartCode ViewerX Crack

SmartCode ViewerX VNC 查看器 ActiveX 毫不费力地将 VNC 查看器功能添加到您的应用程序 SmartCode ViewerX VNC 查看器 ActiveX 使开发人员可以使用一组直观的 ActiveX 属性和方法完全访问 VNC 查看器功能。借助ViewerX 控件,开发人员可以轻松地为其应用程序提供…

<呕心沥血>一文总结数据结构八大排序(持续更新)

目录 一、常见的八大排序 二、八大排序的算法思想 1、冒泡排序 2、选择排序 3、插入排序 4、希尔排序 5、归并排序 6、快速排序 7、堆排序 8、计数排序 三、八大排序的算法实现 一、常见的八大排序 常见的八大排序算法如下: 冒泡排序(Bubble …

Android中的接口回调机制

文章目录1.回调的含义和用途2.java实现接口回调3.Android中接口回调的体现4.接口回调在异步任务中的体现1.回调的含义和用途 一般来说,模块之间都存在一定的调用关系,从调用方式上看,可以分为三类同步调用、异步调用和回调。同步调用是一种阻…

JAVAWeb04-DOM

1. DOM 1.1 概述 1.1.1 官方文档 地址: https://www.w3school.com.cn/js/js_htmldom.asp 1.1.2 DOM 介绍 DOM 全称是 Document Object Model 文档对象模型就是把文档中的标签,属性,文本,转换成为对象来管理 1.2 HTML DOM(文档…

为什么现代企业都在使用ERP系统 它有哪些优势

随着科技的不断发展,企业管理方式也在不断地发生改变。在这个信息化的时代,企业要想取得成功,必须要善于利用先进的信息化技术工具。其中,ERP系统是企业管理中不可或缺的重要工具。本文将探讨现代企业为什么会使用ERP系统&#xf…

CPU占用率高怎么办?正确解决方法在这里!

案例:CPU占用率高怎么解决 【各位朋友,我的电脑现在运行太慢了,同事说可能是CPU占用率太高了,但对本电脑小白来说,完全不知道怎么处理,大家有什么好的方法可以解决这个问题吗?】 在计算机中&a…

快看这些wireshark 命令,必须得会!

wireshark捕获命令 捕获器表达式语法: 限定词三类 Type:host、net、prot 指出其后数字或名字的意义(主机,网段,端口) Direction:src、dst 指出传输方向 (源 、目的) …

GcExcel Java Edition 6.0.6 Crack

概述 GrapeCity Documents for Excel,Java 版,是一个编程接口,允许 Java 开发人员以编程方式大规模创建和操作 Excel 文档。GrapeCity Documents for Excel 是一种解决方案,允许开发人员跨 Java 应用程序导入/导出、创建报告和模板…

论文阅读《GlueStick: Robust Image Matching by Sticking Points and Lines Together》

论文地址:https://arxiv.org/abs/2304.02008 源码地址:https://github.com/cvg/GlueStick 概述 针对视角变化时在闭塞、无纹理、重复纹理区域的线段匹配难的问题,本文提出一种新的匹配范式(GlueStick),该方…

MySQL性能优化(三)事务与锁详解

文章目录什么是数据库事务?事务的四大特性:ACID事务的开启与结束案例表结构与数据案例事务并发的三大问题:脏读(一个事务读取到了其他事务未提交的数据)不可重复读(一个事务读取到其他事务已提交的数据造成…

Qt在安卓手机输出‘hello,world‘

我也想实现这样的功能。 最开始的参考文章: (2条消息) Qt android 开发环境搭建_逝水流年丶轻染尘的博客-CSDN博客 方案1:(失败) 我之前已经下载过 Qt5.14.2了,所以我想直接添加组件 中间过程参考: (2条消息) Qt更新组件出现&…

敏捷开发模式下如何用 PingCode 这类工具迭代管理

迭代(Sprint)是 Scrum 敏捷开发框架的核心,正确的迭代可以帮助敏捷团队提高工作交付速度。Scrum 团队以完成迭代待办列表为工作目标,并在迭代结束时交付一定的产品增量。PingCode 以产品待办列表作为迭代管理的核心,因…