When using Json.stringify () as the JSON specification for object serialization, this property is ignored if a property is a function.
const data1 = { a: ‘aaa‘, fn: function() { return true }}JSON.stringify(data)// 结果是 "{"a":"aaa"}"
In another case, the value of a property isundefined
const data2 = { a: ‘abc‘, b: undefined}JSON.stringify(data2)// 结果是 "{"a":"abc"}"
If the property is True null , this property can be serialized normally:
const data3 = { a: ‘abc‘, b: null}JSON.stringify(data3)// 结果是 "{"a":"abc","b":null}"
nullexecution will not be processed because it can represent an assignment that is undefined and not undefined assigned a value JSON.stringify .
stringifyFunction
stringifyThe function is defined asJSON.stringify(value [, replacer [, space]])
I don't usually have two optional parameters, replacer and space.
valueParameter not many explanation, replacer is actually a custom function, can change JSON.stringify the behavior, space is formatted output, the maximum value is 10, non-integer value is 1
stringifyOutputFunction
In essence no matter how to change, stringify or will not output Function , but Function can call toString() the method, so the idea is very clear.
Const DATA1 = {A:' AAA ', fn:function() {ReturnTrue}}const replace = function (k, v) {if (typeof v = = = ' function ') {return function. Prototype. tostring. call (v)} return v} json. stringify (data1, replace)//result "{" a " : "AAA", "FN": "
The same can be proven undefined to output
const replace = function(k ,v) { if(v === undefined){ return ‘undefined‘ } return v}
stringifyFormatted output
JSON.stringifyThe third parameter is very simple, the equivalent of our editor'stab_size
Const DATA4 = {A:' ABC ',B:null, c: { x: ' xxx ', y: ' yyy ', z: 2046}, D: 9527}json.stringify (DATA4, nul L, 2); //Output result */*"{" A":" ABC"," b": null," C": {" x":" XXX"," Y":" yyy"," Z ": 2046}," D ": 9527}" */
toJSONMethod
toJSONis a cover function, try to use less, read the code to understand:
const data5 = { a: ‘abc‘, b: null, c: { x: ‘xxx‘, y: ‘yyy‘, z: 2046 }, d: 9527, toJSON: function() { return ‘WTF‘ }}JSON.stringify(data5, null, 2);// 结果返回 "WTF"
Deep use Json.stringify ()