Suxue cold sound
JSON
history
Douglas Crockford (yes, the guy who came up with the original inheritance) discovered JSON in 2001. Douglas claimed to have discovered, not invented, it because it was there. In fact, JSON prototypes have been around since 1996. JSON is a syntax for serializing objects, arrays, values, strings, booleans, and NULL. It is based on JavaScript syntax, which is a subset of JavaScript expression syntax. It should follow two principles:
- Strings must be in double quotes, string literals are invalid (
'obj'
) - Property keys must also use double quotes.
JSON.stringify()
Json. stringify(value, replacer? , space?)
Optional parametersreplacer
Used to replace the value parameter before conversion. Details are as follows:
- The node-access function converts the value of a tree node before the value is converted to a string:
// When serialization hits a value, multiply by 2
function replacer(key, value){
if(typeof value === 'number'){
value = 2 * value
}
return value
}
/ / call
JSON.stringify({ a: 5.b: [2.3] }, replacer)
/ / the result
"{"a": 10,"b": [4, 6]}"
Copy the code
- Attribute key whitelist, used to hide all attributes that are not in the list of non-array objects whose attributes are not in the list:
JSON.stringify({ foo: 1.bar: {foo: 1.bar: 1}},'bar'])
/ / the result
"{"bar": {"bar": 1}"
Copy the code
// Is invalid for arrays
JSON.stringify([2.4], ['0'])
/ / the result
"[2, 4]"
Copy the code
Optional parametersspace
It affects the output format, and new lines can be inserted and indented by nesting arrays and objects:
digital
If it is a number, each level is indented more than the previous level in stringification. Spaces less than 0 are interpreted as 0, and Spaces greater than 10 are interpreted as 10:
JSON. Stringify ({foo: 1, the bar: {foo: 1, the bar: 1}}, null, 4) / / output "{" foo" : 1, "bar" : {" foo ": 1," bar ": 1}}"Copy the code
string
If it is a string, then each level has one more indent (or the first ten characters of the string) than the previous level:
JSON.stringify({ foo: 1, bar: {foo: 1, bar: 1} }, null, "--") / / output"{-"foo": 1, -"bar": {-- -- -- -- -- -- -- --"foo": 1, -- -- -- -- -- -- -- --"bar": 1}}"
Copy the code
beJSON.stringify
Ignored data
- Only self-enumerable properties are considered
var obj = Object.defineProperty({}, 'foo', {enumerable: false.value: 7})
JSON.stringify(obj) / / "{}"
Copy the code
- Ignore unsupported values, that is, except for objects, arrays, numerals, strings, booleans, and
null
Any value other than. Like the function, the value of Symbol,undefined
Etc, will returnundefined
. If the property value is one of these values, the property is ignored and parsed into the arraynull
:
JSON.stringify(function (){}) // undefined
JSON.stringify({foo: function (){}})/ / "{}"
JSON.stringify([function (){})// "[null]"
Copy the code
toJSON(key)
methods
If a serialized object has a toJSON method, the toJSON method overrides the object’s default serialization behavior: instead of the object being serialized, the return value from the call to toJSON is serialized:
var x = {
toJSON: function (){
return {x:1}}}JSON.stringify(x) // "{"x":1}"
JSON.stringify({a: x}) // "{"a":{"x":1}}"
Copy the code
The toJSON() method can take a positional argument key, which is always a string with the following values:
- The root location,
""
- Property value, which is the property key
- Array element with a value of index string
var x = {
toJSON: function (key){
console.log(key)
return 1}}JSON.stringify(x) / / print ""
JSON.stringify({a: x}) / / print "a"
JSON.stringify([x]) / / print "0"
Copy the code
JSON.parse()
Json. parse(text, Reviver?) .
JSON.parse(""string"") // Uncaught SyntaxError: missing ) after argument list
JSON.parse('"string"') // "string"
JSON.parse('1') / / 1
JSON.parse('[1]') / / [1]
JSON.parse('[1]') / / Uncaught SyntaxError. Ending with a comma is not allowed
JSON.parse('{"x":1}') // {x:1}
Copy the code
“”stirng”” is not supported by JS, although it is a standard JSON string. You can use ‘string’ instead. If you really need such a form, use json.stringify (“”)
revier
parameter
It is a node access function. It can be used to transform parsed data:
// Convert dates in JSON strings
function dateReviver(key, value){
if (typeof value === 'string') {
var x = Date.parse(value)
if (!isNaN(x)) {
return new Date(x)
}
}
return value
}
var str = '{" name ":" suxue ", "date" : "the 2019-04-21 T22:00:00. 00 z"}'
JSON.parse(str, dateReviver) // {name: "suxue", date: Apr 22 2019 06:00:00 GMT+0800}
Copy the code
Node access function
Json.parse () and json.stringify () can both be passed a function to convert the data:
JSON.stringify()
You can change data before converting it to JSON.JSON.parse()
Parse the JSON, and you can postprocess the resulting data.
Node access function structure is as follows:
function nodeVisitor(key, value) / /thisRefers to the parent element of the current nodeCopy the code
The key value is the same as the key received by toJSON(). The root node has no parent element. When root is accessed, a pseudo-parent element is created with the value:
this
Point to the{'': root}
,root indicates the root nodekey
是' '
value
是root
function nodeVisitor(key, value) {
console.log(this, key, value)
return value
}
This :{"":{x:1}}, key:"", value:{x:1}
// This: {x:1}, key: "x", value: 1
JSON.stringify({x:1},nodeVisitor)
// first: this: {"":{x:1}} key:"" value:{x:1}
This :{a:1} key: "x" value :{a:1}
// ...
JSON.stringify({x: {a:1}},nodeVisitor)
Copy the code
Node access functions must specify their return value:
- Return value without modification.
- Returns a different value to replace the current node.
- return
undefined
, the current node is deleted.
// If no return value is specified, the root node is deleted
function nodeVisitor(key, value) {
console.log(this, key, value)
}
JSON.stringify({x:1},nodeVisitor) // undefined
Copy the code
With the node access function, you can check how the JSON method traverses the data.
How does JSON access data
JSON.stringify()
A particular root node is accessed first using a sequential traversal algorithm (parent elements precede child elements).
JSON.stringify({x:1},nodeVisitor){x:1} => 1
JSON.stringify({x: {a:1}},nodeVisitor)// {x:{a:1}} => {a:1} => 1
Copy the code
JSON.parse()
In the post-order traversal algorithm (the child element precedes the parent element), the leaf node is accessed first.
JSON.parse('{"x":1}', nodeVisitor) 1 => {x:1}
JSON.parse('{"x":{"a":1}}', nodeVisitor) // 1 => {a:1} => {x:{a:1}
Copy the code