Json.stringify () accepts two additional parameters in addition to the JS object to serialize, which specify how the JS object should be serialized. The first argument is a filter, which can be an array or a function; The second argument is an option indicating whether to keep the indentation in the JSON string. Using these two parameters individually or in combination gives you more complete and in-depth control over the SERIalization of JSON.

1. Filtering results

If the filter argument is an array, the result of json.stringify () will contain only the properties listed in the array.

let book = {
    'title':'profession'.'authors': ['yk'],
    edition:3,
    year:2020
}

let jsonText = JSON.stringify(book,['title'.'edition']);
Copy the code

The jsonText obtained is:

{'title':'profession',edition:3}
Copy the code

Look at an example of a function passed in below

let book = {
    'title':'profession'.'authors': ['yk'],
    edition:3,
    year:2020
}

let jsonText = JSON.stringify(book,function(key, value){
    switch(key) {
        case "authors":
            return value.join(",")
        
        case "year":
            return 5000;
            
        case "edition":
            return undefined;
            
        default:
            returnvalue; }});Copy the code

The key must be a string. If the function returns undefined, the corresponding attribute is ignored.

So what we get up here is zero

{'title':'profession'.'authors':'yk',year:5000}
Copy the code

two Json. stringify’s string indentation function

The third argument to the json.stringify () method controls indentation and whitespace in the result. If this parameter is a numeric value, it represents the number of Spaces indented at each level. For example, to indent 4 Spaces per level:

let book = {
    'title':'profession'.'authors': ['yk'
    ],
    edition:3,
    year:2020
}

let jsonText = JSON.stringify(book,null,4);
Copy the code

The resulting jsonText is:

let book = {
        'title':'profession'.'authors': ['yk'
        ],
        edition:3,
        year:2020
}
Copy the code
⚠ The value ️ cannot exceed 10. If the value exceeds 10, handle it as 10. Interestingly, if the indent argument is a string rather than a number, the string is treated as an indent (no Spaces are used)Copy the code
let jsonText = JSON.stringify(book,null,"--"); I get jsontext {--'title':'profession', -'authors': -'yk'
--],
--edition:3,
--year:2020
}
Copy the code

Similarly, the number of indent characters cannot exceed 10. If more than 10 characters are indent, only the first 10 characters will appear

Scan code plus group, daily update a front-end technology article grow together.