前端Q

我是winty,专注分享前端知识和各类前端资源,乐于分享各种有趣的事,关注我,一起做个有趣的人~

公众号

点击上方 前端Q,关注公众号

回复加群,加入前端Q技术交流群

英文 | https://javascript.plainenglish.io/as-a-front-end-engineer-9-secrets-about-json-stringify-you-should-know-about-e71c175f40d8

作为前端开发工程师,你一定用过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 referenceconst isCyclic = (obj) => {// Use the Set data type to store detected objectslet stackSet = new Set()let detected = falseconst detect = (obj) => {// If it is not an object type, you can skip it directlyif (obj && typeof obj != 'object') {return}// When the object to be checked already exists in the stackSet, it means that there is a circular referenceif (stackSet.has(obj)) {return detected = true}// Save the current obj as a stackSetstackSet.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 referencelet 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 bigintif (typeof data === 'bigint') {throw new TypeError('Do not know how to serialize a BigInt')}const type = typeof dataconst commonKeys1 = ['undefined', 'function', 'symbol']const getType = (s) => {return Object.prototype.toString.call(s).replace(/\[object (.*?)\]/, '$1').toLowerCase()}// not an objectif (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 Bigintlet obj1 = { a: 'aa' }
let obj2 = { name: 'fatfish', a: obj1, b: obj1 }
obj2.obj = obj2console.log(jsonstringify(obj2))
// TypeError: Converting circular structure to JSON
console.log(jsonStringify(BigInt(1)))
// TypeError: Do not know how to serialize a BigInt

最后

以上就是我今天跟你分享的全部内容,希望你能从今天的文章中学到新的知识。

最后,感谢你的阅读,祝编程愉快!

往期推荐

vue 中动态引入图片为什么要是 require, 你不知道的那些事

面试官:你确定多窗口之间sessionStorage不能共享状态吗?

深入浅出前端缓存 (收藏!)

最后

  • 欢迎加我微信,拉你进技术群,长期交流学习...

  • 欢迎关注「前端Q」,认真学前端,做个专业的技术人...

前端Q

本公众号主要分享一些技术圈(前端圈为主)相关的技术文章、工具资源、学习资料、招聘信息及其他有趣的东西...

公众号

点个在看支持我吧

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

  1. 2023年了,还有开发人员还不知道commit 规范 ??

    一个开发人员需要知道的 commit 规范 什么是约定式提交 约定式提交(Conventional Commits)是一种用于代码版本控制的规范,旨在通过明确和标准化提交信息来提高代码协作质量和效率. ...

  2. 国内开发人员都不知道阿里软件吗?

    我想未必是大家不知道,而是不去关注. 都在等待. 等待一个新闻?    xxxx年盈利xxx万. 等待一个螃蟹?   路人甲在阿里软件创造奇迹,2月成立公司,1年上市. 等待一个命令?   老板:你们 ...

  3. [转] 你不知道的 JSON.stringify() 的威力

    原文地址: https://github.com/NieZhuZhu/Blog/issues/1 前言 其实有很多有用的东西,当时学习了,也记住了,但是时间久了就是记不住,所以导致在日常开发中总是想不 ...

  4. 测试与开发人员的战斗

    作为一个测试老兵,经常听到有测试新人抱怨,需要和开发人员进行激烈的讨论,感觉像打仗一样.其实,测试人员和开发人员的战斗不仅仅在小公司有,在大型软件公司也是比比皆是.这种战斗不仅仅发生在开发周期的初期, ...

  5. 大多数开发人员都不知道的JSON.stringify 秘密

    作为前端开发工程师,你一定用过JSON.stringify,但你知道它的全部秘密吗? 基本上,JSON.stringify 将对象转换为 JSON 字符串.同时,JSON.stringify 有如下规 ...

  6. 前端:JSON.stringify() 的 5 个秘密特性

    JSON.stringify() 方法能将一个 JavaScript 对象或值转换成一个 JSON 字符串. 作为一名 JavaScript 开发人员,JSON.stringify() 是用于调试的最 ...

  7. javascript 数组和对象的浅复制和深度复制 assign/slice/concat/JSON.parse(JSON.stringify())...

    javascript 数组和对象的浅度复制和深度复制 在平常我们用 '='来用一个变量引用一个数组或对象,这里是'引用'而不是复制下面我们看一个例子引用和复制是什么概念 var arr=[1,2,3, ...

  8. 如何解决使用JSON.stringify时遇到的循环引用问题

    程序员在日常做TypeScript/JavaScript开发时,经常需要将复杂的JavaScript对象通过JSON.stringify序列化成json字符串,保存到本地以便后续具体分析. 然而如果J ...

  9. json.stringify()与json.parse()的区别,json.stringify()的妙用

    一.JSON.stringify()与JSON.parse()的区别 最近做项目,发现JSON.stringify()使用场景真的挺多,我们都知道JSON.stringify()的作用是将 JavaS ...

最新文章

  1. 解决SQL Server里sp_helptext输出格式错行问题
  2. 活动推荐 | 2019日立「视频分析技术黑客马拉松」报名启动,还有高额奖金等你赢...
  3. 线段树专辑——pku 3667 Hotel
  4. 整理一下网上看到的几个巧妙小电路
  5. 两阶段聚合(局部聚合+全局聚合)
  6. 没有bug队——加贝——Python 59,60
  7. 【CCCC】L2-028 秀恩爱分得快 (25分),模拟题
  8. win10安装pytorch很慢,如何解决?
  9. JavaScript:屏蔽浏览器右键点击事件
  10. EXCEL 连接符的使用
  11. Flutter之Widget构建过程详解
  12. 分享Android开发中用到的图标icon设计下载地址
  13. LabVIEW开发实战:Labview简介
  14. carlife android 无线,carlife为什么不能无线连接 不能无线连接解决方法
  15. 不能创建对象qmdispatch_win7系统打开某些软件提示“Activex部件不能创建对象”的解决方法...
  16. 多张eps合并成一张
  17. java咖啡是研磨的吗_研磨咖啡,这三个点一定要注意
  18. 关于取地址运算符以及指针的问题
  19. ASO优化中关于APP推广的一些基本而有效的方法
  20. Mybatis-1.Mybatis概述

热门文章

  1. 学计算机与机械一体哪好,2021机械类最吃香的专业有哪些 前景好吗
  2. 哪款无线耳机通话效果好?无线蓝牙耳机通话效果排名
  3. 用六种算法实现maya动画曲线光滑
  4. rdkit 处理2D、3D分子
  5. 君澜酒店集团打造粤东温泉度假标杆,促进旅游产业升级
  6. CentOS 7中/etc/rc.local开机启动脚本不生效怎么办?
  7. 全国地图json数据/省级数据/市级数据
  8. 黑马程序员 一个程序员的自我修养
  9. restTemplate.postForObject
  10. 传奇外网架设常见的问题及解决办法-传奇创建人物失败/不开门/PAK显示密码错误/脚本错误