There are many common functions in JS. We may use them every day, but we don't know some of their extra functions. JSON.stringify
is such a function. Let’s take a look at its special usage today.
Basics
##The JSON.stringify method receives a variable and It is converted into JSON representation.
const boy = { name: 'John', age: 23 }; JSON.stringify(boy); // {"name":"John","age":23}
const boy = { name: 'John', age: 23, hobbies: new Map([[0, 'coding'], [1, 'earn money']]) } JSON.stringify(boy) // {"name":"John","age":23,"hobbies":{}}
The second parameter
JSON.stringify can receive the second parameter, which can be called
replacer Replacer.
const boy = { name: 'John', age: 23 } JSON.stringify(boy, ['name']) // {"name":"John"}
replacer parameter can also receive a function. This function iterates through the entire object, passing in the keys and values, and lets you decide how to replace them.
const boy = { name: 'John', age: 23, hobbies: new Map([[0, 'coding'], [1, 'earn money']]) } JSON.stringify(boy, (key, value) => { if (value instanceof Map) { return [...value.values()] } return value }) // {"name":"John","age":23,"hobbies":["coding","earn money"]}
undefined (returning
null is not acceptable), this attribute will be removed:
JSON.stringify(boy, (key, value) => { if (typeof value === 'string') { return undefined } return value }) // {"age":23,"hobbies":{}}
The third parameter
The third parameterspace controls the spacing of the converted JSON string.
JSON.stringify(boy, null, 2) // { // "name": "John", // "age": 23, // "hobbies": {} // }
JSON.stringify(boy, null, '--') // { // --"name": "John", // --"age": 23, // --"hobbies": {} // }
toJSON method
If the object we want to convert has atoJSON method, then we can customize the process of being serialized. . Instead of serializing the object, you can return a new value from the method, and this value will be serialized instead of the original object.
const boy = { name: 'John', age: 23, hobbies: new Map([[0, 'coding'], [1, 'earn money']]), toJSON() { return { name: `${this.name} (${this.age})`, favorite: this.hobbies.get(0) } } } JSON.stringify(boy) // {"name":"John (23)","favorite":"coding"}
Reference article
js tutorial column, welcome to learn!
The above is the detailed content of Little-known uses of JSON.stringify. For more information, please follow other related articles on the PHP Chinese website!