JSON in JavaScript

JSON syntax supports three types:

  1. Simple values: strings, values, and null can appear in JSON, but undefined cannot

    (The absence of undefined in JSON is a drawback of using json for deep copy)

    let obj = {
      "name": "snake".t_underfined: undefined.t_null: null
    }
    let j1 = JSON.stringify(obj)//{"name":"snake","t_null":null}
    Copy the code
  2. object

    Objects in JSON must enclose property names in double quotes

    {
        "name": "snake"."t_null": null
    }
    Copy the code
  3. An array of

Parsing and serialization

JSON. Stringify (), JSON. The parse ()

1 the serialization

Json.stringify (), in addition to accepting the object to be serialized, can also accept two additional arguments, one for filtering the result and one for indenting the string:

1.1 Filtration Results

  • The second argument is an array, and json.stringify () returns a result that contains only the properties listed in the array

    let book = {
      title: "javaScript".authors: [
        "rose"."jack"].edition: 4
    }
    let jsonText = JSON.stringify(book,['title'.'authors'])
    console.log(jsonText);
    //{"title":"javaScript","authors":["rose","jack"]}
    Copy the code
  • The second argument is the replacer, which provides a key,value. The key is always a string and can be used to perform operations on the property. Return undefined the value disappears

    let jsonText = JSON.stringify(book, (key, value) = > {
      switch(key) {
        case "authors":
          return value.join("+")
        case "edition":
          return undefined // Because JSON is not underpay, the serialized edition will disappear
        default:
          return value
      }
    })
    // {"title":"javaScript","authors":"rose+jack"}
    console.log(jsonText);
    Copy the code

1.2 Indentation of strings

If this parameter is numeric, it means that the maximum number of Spaces for each level of indentation is 10.

Is a string, the string is indented. Similarly, if the string length exceeds 10, only the first 10 coordinates [0-9] are taken.

In addition to indentation json.stringify () also inserts newlines automatically.

let jsonText = JSON.stringify(book, null.4)
console.log(jsonText);
{
    "title": "javaScript"."authors": [
        "rose"."jack"]."edition": 4
}
Copy the code

Use the string “– “to get a more intuitive feel:

let jsonText = JSON.stringify(book, null."--")
console.log(jsonText); {-"title": "javaScript", -"authors": [-- --"rose", -- -"jack"-, -"edition": 4
}
Copy the code

1.3 toJSON () method

Here’s the toJSON() method added using ES6 syntax. The arrow function cannot be used to define the toJSON() method, mainly because the lexical scope of the arrow function is global.

let book2 = {
  title: "javaScript".authors: [
    "rose"."jack"].edition: 4.toJSON(){
    return this.title
  }
}
let jsonText = JSON.stringify(book2)
console.log(jsonText);//"javaScript"
Copy the code

Note: The Date object has the toJSON() method, which automatically converts the JavaScript Date object to an ISO 8601 Date string.

You can customize the reviver function of the parse procedure to return a Date object

1.4 Serialization process **

1. If toJSON() is present, the toJSON() method value is called, otherwise the default serialization is used

2. If a second argument is provided (see 1.1), the filter is applied. The value passed in to the filter function is the value returned in Step 1

3. The value returned in step 2 is serialized accordingly, i.e., repeat steps 1,2, and 3

2 Parsing Options

The json.parse () method can take an additional argument, which is a function called a reviver, and return undefined means that the corresponding value and value will be lost

The following code is the result of book2 being serialized (son.stringify ()) and then parsed (json.parse ()). The date object was converted into a string by its own toJSON() when it was serialized and parsed as a string

let book2 = {
  title: "javaScript".authors: [
    "rose"."jack"].edition: 4.date: new Date()}let jsonText = JSON.stringify(book2)
let book3 = JSON.parse(jsonText)
console.log(book2);
// { title: 'javaScript',
// authors: [ 'rose', 'jack' ],
// edition: 4,
/ / date: 2021-04-12 T08:38:59. 420 z}
console.log(book3);
// { title: 'javaScript',
// authors: [ 'rose', 'jack' ],
// edition: 4,
// date: '2021-04-12t08:38:59.420z'} where date becomes a string
Copy the code

A second argument can be added to restore date:

let book4 = JSON.parse(jsonText, (key, value) = > 
      key === "date" ? new Date(value) : value )// If it is passed as date, convert to date (), otherwise unchanged
console.log(book4);
// { title: 'javaScript',
// authors: [ 'rose', 'jack' ],
// edition: 4,
// Date: 2021-04-12t08:43:31.641z
Copy the code

reference

JavaScript Advanced programming Chapter 23 JSON