当前位置:网站首页>Learn json.stringify again
Learn json.stringify again
2022-07-27 00:46:00 【Bug I'll write it】
Relearning JSON.stringify
I once encountered a problem , Use JSON.stringify Found some when key Null values are ignored after serialization
let signInfo = [
{
fieldId: 539,
value: undefined
},
{
fieldId: 540,
value: undefined
},
{
fieldId: 546,
value: undefined
},
]
// after JSON.stringify Later data , Less value key, This causes the backend to fail to read value Value to report an error
// The reason is that `undefined`、` Any function ` as well as `symbol value `, Appear in the ` Non array objects ` Is ignored during serialization
console.log(JSON.stringify(signInfo))
// '[{"fieldId":539},{"fieldId":540},{"fieldId":546}]'
resolvent
let newSignInfo = signInfo.map(item => ({
...item, value: item.value === undefined ? '' : item.value }));
console.log(JSON.stringify(newSignInfo))
// '[{"fieldId":539,"value":""},{"fieldId":540,"value":""},{"fieldId":546,"value":""}]'
Or use it directly JSON.stringify Second parameter of
// Judged value by undefined, Return an empty string
JSON.stringify(signInfo, (key, value) => value === undefined ? '' : value)
// '[{"fieldId":539,"value":""},{"fieldId":540,"value":""},{"fieldId":546,"value":""}]'
grammar
JSON.stringify(value[, replacer [, space]])
Parameters
value- To sequence into One JSON The value of the string .
replacerOptional- If the parameter is a function , During serialization , Each property of the serialized value is transformed and processed by this function ;
- If the parameter is an array , Only the property names contained in this array will be serialized to the final JSON In a string ;
- If the parameter is null Or not provided , All properties of the object will be serialized .
spaceOptional- Specifies the blank string for indentation , Used to beautify the output (pretty-print);
- If the parameter is a number , It represents how many spaces there are ; Cap of 10.
- If the value is less than 1, It means there are no spaces ;
- If the parameter is a string ( When the string length exceeds 10 Letters , Before 10 Letters ), The string will be treated as a space ;
- If this parameter is not provided ( Or for null), There will be no spaces .
Return value
A representation of a given value JSON character string .
abnormal
JSON.stringifyYou can convert objects or values ( We usually use more conversion objects )- You can specify
replacerSelective substitution for functions - You can also specify
replacerIs an array , The specified attribute can be converted
It's just MDN on JSON.stringify The most basic description , Let's try these features first
// 1. Convert objects
console.log(JSON.stringify({
name: ' Zhang San ', sex: 'boy' })) // '{"name":" Zhang San ","sex":"boy"}'
// 2. Convert normal values
console.log(JSON.stringify(' Zhang San ')) // " Zhang San "
console.log(JSON.stringify(1)) // "1"
console.log(JSON.stringify(true)) // "true"
console.log(JSON.stringify(null)) // "null"
// 3. Appoint replacer function
console.log(JSON.stringify({
name: ' Zhang San ', sex: 'boy', age: 100 }, (key, value) => {
return typeof value === 'number' ? undefined : value
}))
// '{"name":" Zhang San ","sex":"boy"}'
// 4. Specify array
console.log(JSON.stringify({
name: ' Zhang San ', sex: 'boy', age: 100 }, [ 'name' ]))
// '{"name":" Zhang San "}'
// 5. Appoint space( Beautify the output )
console.log(JSON.stringify({
name: ' Zhang San ', sex: 'boy', age: 100 }))
// '{"name":" Zhang San ","sex":"boy","age":100}'
console.log(JSON.stringify({
name: ' Zhang San ', sex: 'boy', age: 100 }, null , 2))
/* { "name": " Zhang San ", "sex": "boy", "age": 100 } */
9 Big characteristic
Characteristic 1
undefined、Any functionas well assymbol value, Appear in theNon array objectsIs ignored during serializationundefined、Any functionas well assymbol valueAppear in theArrayWill be converted tonull.undefined、Any functionas well assymbol valueWhen converted separately , Returns theundefined
// 1. The existence of these three values in the object will be ignored
console.log(JSON.stringify({
name: ' Zhang San ',
sex: 'boy',
// Functions are ignored
showName () {
console.log(' Zhang San ')
},
// undefined Will be ignored
age: undefined,
// Symbol Will be ignored
symbolName: Symbol(' Zhang San ')
}))
// '{"name":" Zhang San ","sex":"boy"}'
// 2. There are three values in the array that will be converted to null
console.log(JSON.stringify([
' Zhang San ',
'boy',
// The function will be converted to null
function showName () {
console.log(' Zhang San ')
},
//undefined Will be converted to null
undefined,
//Symbol Will be converted to null
Symbol(' Zhang San ')
]))
// '[" Zhang San ","boy",null,null,null]'
// 3. A separate conversion returns undefined
console.log(JSON.stringify(
function showName () {
console.log(' Zhang San ')
}
)) // undefined
console.log(JSON.stringify(undefined)) // undefined
console.log(JSON.stringify(Symbol(' Zhang San '))) // undefined
Characteristic 2
Boolean value、Numbers、character stringThe wrapper object will be automatically converted to the corresponding original value during serialization .
console.log(JSON.stringify([new Number(1), new String(" Zhang San "), new Boolean(false)]))
// '[1," Zhang San ",false]'
Characteristic 3
All with
symbolAttributes that are attribute keys are completely ignored , Even ifreplacerThe mandatory specification in the parameter contains them .
console.log(JSON.stringify({
[Symbol(' Zhang San ')]: ' Zhang San '}
))
// '{}'
console.log(JSON.stringify({
[ Symbol(' Zhang San ') ]: ' Zhang San ',
}, (key, value) => {
if (typeof key === 'symbol') {
return value
}
}))
// undefined
Characteristic 4
NaNandInfinityThe value of the format andnullWill be treated asnull.
console.log(JSON.stringify({
age: NaN,
age2: Infinity,
name: null
}))
// '{"age":null,"age2":null,"name":null}'
Characteristic 5
Conversion value, if any
toJSON()Method , This method defines what values will be serialized .
const toJSONObj = {
name: ' Zhang San ',
toJSON () {
return 'JSON.stringify'
}
}
console.log(JSON.stringify(toJSONObj))
// "JSON.stringify"
Characteristic 6
DateThe date calledtoJSON()Convert it to string character string ( Same asDate.toISOString()), So it's treated like a string .
const d = new Date()
console.log(d.toJSON()) // 2021-10-05T14:01:23.932Z
console.log(JSON.stringify(d)) // "2021-10-05T14:01:23.932Z"
Feature seven
For objects that contain circular references ( Objects refer to each other , Forming an infinite cycle ) Perform this method , Will throw an error .
let cyclicObj = {
name: ' Zhang San ',
}
cyclicObj.obj = cyclicObj
console.log(JSON.stringify(cyclicObj))
// Converting circular structure to JSON
Characteristic eight
Other types of objects , Include Map/Set/WeakMap/WeakSet, Only enumerable properties... Will be serialized
let enumerableObj = {
}
Object.defineProperties(enumerableObj, {
name: {
value: ' Zhang San ',
enumerable: true
},
sex: {
value: 'boy',
enumerable: false
},
})
console.log(JSON.stringify(enumerableObj))
// '{"name":" Zhang San "}'
Feature 9
When trying to convert BigInt The value of type will throw an error
const alsoHuge = BigInt(9007199254740991)
console.log(JSON.stringify(alsoHuge))
// TypeError: Do not know how to serialize a BigInt
Writing a JSON.stringify
Finally finish learning again JSON.stringify Many features of ! Let's write a simple version based on these features ( nothing replacer Functions and space)
The source code to achieve
const jsonstringify = (data) => {
// Confirm whether there is a circular reference to an object
const isCyclic = (obj) => {
// Use Set Data type to store detected objects
let stackSet = new Set()
let detected = false
const detect = (obj) => {
// If it's not an object type , You can skip
if (obj && typeof obj != 'object') {
return
}
// When the object to be checked already exists in stackSet In the middle of the day , Indicates that there is a circular reference
if (stackSet.has(obj)) {
return detected = true
}
// Will the current obj Save as stackSet
stackSet.add(obj)
for (let key in obj) {
// Yes obj Check the properties under one by one
if (obj.hasOwnProperty(key)) {
detect(obj[key])
}
}
// After the leveling test is completed , Delete the current object , Prevent misjudgment
/* for example : The properties of the object point to the same reference , If not deleted , Will be considered a circular reference let tempObj = { name: ' Zhang San ' } let obj4 = { obj1: tempObj, obj2: tempObj } */
stackSet.delete(obj)
}
detect(obj)
return detected
}
// Feature seven :
// For objects that contain circular references ( Objects refer to each other , Forming an infinite cycle ) Perform this method , Will throw an error .
if (isCyclic(data)) {
throw new TypeError('Converting circular structure to JSON')
}
// Feature 9 :
// When trying to convert BigInt The value of type will throw an error
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()
}
// The object
if (type !== 'object' || data === null) {
let result = data
// Characteristic 4 :
// NaN and Infinity The value of the format and null Will be treated as null.
if ([NaN, Infinity, null].includes(data)) {
result = 'null'
// Characteristic 1 :
// `undefined`、` Any function ` as well as `symbol value ` By ` Separate conversion ` when , Returns the undefined
} else if (commonKeys1.includes(type)) {
// Directly obtained undefined, It's not a string 'undefined'
return undefined
} else if (type === 'string') {
result = '"' + data + '"'
}
return String(result)
} else if (type === 'object') {
// Characteristic 5 :
// Conversion value, if any toJSON() Method , This method defines what values will be serialized
// Characteristic 6 :
// Date The date called toJSON() Convert it to string character string ( Same as Date.toISOString()), So it's treated like a string .
if (typeof data.toJSON === 'function') {
return jsonstringify(data.toJSON())
} else if (Array.isArray(data)) {
let result = data.map((it) => {
// Characteristic 1 :
// `undefined`、` Any function ` as well as `symbol value ` Appear in the ` Array ` Will be converted to `null`
return commonKeys1.includes(typeof it) ? 'null' : jsonstringify(it)
})
return `[${
result}]`.replace(/'/g, '"')
} else {
// Characteristic 2 :
// Boolean value 、 Numbers 、 The wrapper object of a string is automatically converted to its original value during serialization .
if (['boolean', 'number'].includes(getType(data))) {
return String(data)
} else if (getType(data) === 'string') {
return '"' + data + '"'
} else {
let result = []
// Characteristic eight
// Other types of objects , Include Map/Set/WeakMap/WeakSet, Only enumerable properties... Will be serialized
Object.keys(data).forEach((key) => {
// Characteristic 3 :
// All with symbol Attributes that are attribute keys are completely ignored , Even if replacer The mandatory specification in the parameter contains them .
if (typeof key !== 'symbol') {
const value = data[key]
// Characteristic 1
// `undefined`、` Any function ` as well as `symbol value `, Appear in the ` Non array objects ` Is ignored during serialization
if (!commonKeys1.includes(typeof value)) {
result.push(`"${
key}":${
jsonstringify(value)}`)
}
}
})
return `{
${
result}}`.replace(/'/, '"')
}
}
}
}
边栏推荐
- Viterbi Viterbi decoding bit error rate simulation, modulation is QPSK, channel is Gaussian white noise
- 9_ Logistic regression
- Blue Bridge Cup 1004 [recursive] cow story
- DOM day_04(7.12)BOM、打开新页面(延迟打开)、地址栏操作、浏览器信息读取、历史操作
- 用New,delete和用malloc,free申请,释放堆区空间
- 【Codeforces Round #808 (Div 2.) A·B·C】
- Detailed explanation of CSRF forged user request attack
- 6_梯度下降法(Gradient Descent)
- 【4.2 约数】
- ArcGIS and CASS realize elevation points of cross-section Exhibition
猜你喜欢

Matlab simulation of inverted pendulum control system based on qlearning reinforcement learning

AutoCAD的卸载后重新安装,删除注册表的详细过程

【4.9 容斥原理详解】
![[PCB open source sharing] stc32g12k128/stc8h8k64u development board](/img/f1/48b344722820ab262e751aebf65411.png)
[PCB open source sharing] stc32g12k128/stc8h8k64u development board

Operator overloading

Linux系统中安装Redis-7.0.4
![[Qt]容器类、迭代器、foreach关键字](/img/88/d9d5be096009b4e5baa0966e6f292c.jpg)
[Qt]容器类、迭代器、foreach关键字

DOM day_03(7.11) 事件冒泡机制、事件委托、待办事项、阻止默认事件、鼠标坐标、页面滚动事件、创建DOM元素、DOM封装操作

Based on the theoretical principle and simulation results of MATLAB spherical decoding, compare 2norm spherical decoding, infinite norm spherical decoding, ML detection

CDs simulation of minimum dominating set based on MATLAB
随机推荐
【4.10 博弈论详解】
【 Educational Codeforces Round 132 (Rated for Div. 2) A·B·C】
[Qt]属性
[qt] meta object system
箭头函数详解 2021-04-30
Dynamic binding, static binding, and polymorphism
JSCORE day_02(7.1)
Install redis-7.0.4 in Linux system
八皇后 N皇后
JS screen detection method summary 2021-10-05
关于Redis问题的二三事
AutoCAD的卸载后重新安装,删除注册表的详细过程
Operator overloading
QML type system
Use of postman
【2. Tmux 操作】
简单的素数程序 初学者 希望码龄高的大佬可以一下
Input a string of letters and output the vowels inside. I hope you guys can give guidance
10个Web API
【4.4 快速幂详解及快速幂求逆元】