Home > Web Front-end > JS Tutorial > Little-known uses of JSON.stringify

Little-known uses of JSON.stringify

青灯夜游
Release: 2019-11-30 17:39:12
forward
3070 people have browsed it

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.

Little-known uses of JSON.stringify

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}
Copy after login
JSON is a pure string, which is essentially a subset of JS, so not all JS objects can be converted to JSON:

const boy = { 
  name: 'John', 
  age: 23,
  hobbies: new Map([[0, 'coding'], [1, 'earn money']])
}

JSON.stringify(boy)
// {"name":"John","age":23,"hobbies":{}}
Copy after login
In the above example, the Map object is Will be ignored and converted to a normal object. If the attribute is a function, this attribute will be ignored. Interested students can try it.

The second parameter

JSON.stringify can receive the second parameter, which can be called replacer Replacer.

You can pass in a string array, and only the properties in this array will be converted, just like a whitelist.

const boy = { 
  name: 'John', 
  age: 23
}

JSON.stringify(boy, ['name'])
// {"name":"John"}
Copy after login
We can use this feature to convert only the attributes that need to be converted, and filter out long arrays, error objects, etc.

This

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"]}
Copy after login
And if you return

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":{}}
Copy after login

The third parameter

The third parameter

space controls the spacing of the converted JSON string.

If the parameter is a number, the number of spaces will be used for indentation:

JSON.stringify(boy, null, 2)
// {
//   "name": "John",
//   "age": 23,
//   "hobbies": {}
// }
Copy after login
And if the parameter is a string, the indentation will be based on the string:

JSON.stringify(boy, null, '--')
// {
//   --"name": "John",
//   --"age": 23,
//   --"hobbies": {}
// }
Copy after login

toJSON method

If the object we want to convert has a

toJSON 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"}
Copy after login
Isn’t it interesting? Sometimes it is useful to read some documents carefully~

Reference article

  • Original address: https:// mp.weixin.qq.com/s/_e83_G7RjVt2eR_ro7blOA

  • MDN:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON /stringify

This article comes from the

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template