JavaScript has many functions that do their job. We use them every day, but don’t know their extra features. It was only when we looked at the documents one day that we realized that they had more functionality than we had imagined. Json.stringify is one of them. Today we are going to talk about this hidden power player.

Basic usage

The json.stringify method takes an argument and converts it to a JSON string form.

const firstItem = { 
  title: 'Transformers', year: 2007 }; JSON.stringify(firstItem); / / {'title':'Transformers'.'year': 2007}Copy the code

The problem arises when an element cannot be serialized as a JSON string.

const secondItem = { 
  title: 'Transformers', 
  year: 2007, 
  starring: new Map([[0, 'Shia LaBeouf'], [1,'Megan Fox']]) 
};

JSON.stringify(secondItem);
// {'title':'Transformers'.'year': 2007,'starring': {}}Copy the code

Second parameter

Json.stringify also has a second argument, called the substitution argument.

You can pass an array of strings as a whitelist of object properties that will be included in the output.

JSON.stringify(secondItem, ['title']); / / {'title':'Transformers'}

Copy the code

We can filter out some unwanted values. These values are either too large (such as Error objects) or cannot be converted to readable JSON form.

The substitution argument can also be a function. This function takes as arguments the current properties and values as the json.stringify method iterates through the object. If the function does not return any value or returns undefined, the current node will not appear in the result.

JSON.stringify(secondItem, (key, value) => {
  if (value instanceof Map) {
    return [...value.values()];
  }
  returnvalue; }); / / {'title':'Transformers'.'year': 2007,'starring': ['Shia LaBeouf'.'Megan Fox']}

Copy the code

You can remove these attributes from the result by having the function return undefined.

JSON.stringify(secondItem, (key, value) => {
  if (typeof value === 'string') {
    return undefined;
  }
  returnvalue; }); / / {"year": 2007,"starring": {}}Copy the code

The second argument can also be used to create a simple object hash function. It is important to note, however, that json.stringify (obj) does not guarantee the output order of the attributes, which is crucial when serialized results are used for hash/checksum purposes. To do this, we can set the second argument to Object.keys(obj).sort() and the objects will be serialized in this order.

function objectHash(obj: object): string {
  const str = JSON.stringify(obj, Object.keys(obj).sort());
  return createHash('sha1').update(str).digest('hex');
}
Copy the code

The third parameter.

The third argument sets the whitespace indentation in the final string. If the argument is a number, each level of serialization is indented with that number of Spaces.

JSON.stringify(secondItem, null, 2); / / {/ /"title": "Transformers", / /"year": / / 2007"starring": / /} {}Copy the code

If the third argument is a string, it replaces the space character.

JSON.stringify(secondItem, null, '🦄'); / / {/ / 🦄"title": "Transformers", / / 🦄"year": / / 🦄, 2007"starring": / /} {}Copy the code

ToJSON method

If the object we serialize has a toJSON method, it will follow a custom serialization process. You can return a new value in the method, which will be serialized instead of the original object.

const thirdItem = { 
  title: 'Transformers', 
  year: 2007, 
  starring: new Map([[0, 'Shia LaBeouf'], [1,'Megan Fox']]),
  toJSON() {
    return { 
      name: `${this.title} (${this.year})`, 
      actors: [...this.starring.values()] 
    };
  }
};

console.log(JSON.stringify(thirdItem));
// {"name":"Transformers (2007)"."actors": ["Shia LaBeouf"."Megan Fox"]}

Copy the code

The last

Looking at the documentation of the functions we use on a daily basis can sometimes be rewarding. There could be surprises, and we could learn a lot. Keep your thirst for knowledge and keep reading.

Wechat official account: 1024 translation station