For JSON, I believe you should be quite familiar with. You probably work with JSON every day, both on the front end and the back end. JSON, short for JavaScript Object Notation, is a lightweight text data interchange format that is smaller, faster, and easier to parse than XML

In JavaScript,JSON objects contain two methods,parse() and stringify(), the former for deserialization and the latter for serialization. Deserialization is the opposite of serialization, which is commonly understood as turning an object into a string.

Today we’ll focus on the stringify() method. Although we use this method all the time, we tend to overlook further uses of this method. If we can use this method well, we can achieve twice the result with half the effort in the actual development process.

Console. log is often used to print the output. Let’s say we print an object below:

let obj = {
  name:'zhangsan'.age:undefined
}
console.log(obj)  // // {name: "zhangsan", age: undefined}
Copy the code

What attributes are filtered?

The result can be clearly output in the console to achieve the desired result. But let’s say some of the property values in our object are meaningless. For example, in the code below, age is an undefined property and we don’t want to print what to do with it on the console. You can use the json.stringify () method to do the filtering

let obj = {
  name:'zhangsan'.age:undefined
}
console.log(JSON.stringify(obj))  // {"name":"zhangsan"}
Copy the code

We can see that the output has filtered out the age attribute whose value is undefined. This is one of the features of json.stringify (). Values of any function or symbol, except undefined, are also filtered.

let obj = {
  name:'zhangsan'.age:undefined.f:(a)= > { console.log(1)},symbol:Symbol('This is a symbol')}console.log(JSON.stringify(obj))  // {"name":"zhangsan"}
Copy the code

Let’s add another property to this object. This time we’re adding an array that contains some of the types we mentioned above. What’s the result?

let obj = {
  name:'zhangsan'.age:undefined.f:(a)= > { console.log(1)},symbol:Symbol('This is a symbol'),
  arr: [1.undefined.2.this.f, 3.Symbol('This is a symbol in array')]}console.log(JSON.stringify(obj))  // {"name":"zhangsan","arr":[1,null,2,null,3,null]}
Copy the code

As you can see,undefined, function and symbol are null. We’ll test these types again, but what if we manipulated them directly using json.stringify ()?

console.log(JSON.stringify(undefined))  // undefined
console.log(JSON.stringify((a)= > { console.log(1)}))// undefined
console.log(JSON.stringify(Symbol('This is a symbol')))  // undefined
Copy the code

We can see that the output is undefined. Let’s look at some other special values:

console.log(JSON.stringify(null))  // null
console.log(JSON.stringify(NaN))  // null
console.log(JSON.stringify(Infinity))  // null
Copy the code

You can see that null,NaN,Infinity and so on all become NULL.

Let’s look at the results of converting wrapped objects

console.log(JSON.stringify(new String('str')))  // "str"
console.log(JSON.stringify(new Boolean(true)))  // true
console.log(JSON.stringify(new Number(1)))  / / 1
Copy the code

As you can see, wrapper objects for strings, Booleans, and numbers are converted to their original values when serialized

ToJSON () method

If we have the toJSON method in our transform object, it will determine the result returned:

let obj = {
  name:'zhangsan'.toJSON:function(){
    return 'customize return value'}}console.log(JSON.stringify(obj))  // "customize return value"
Copy the code

Undefined if the display defines the toJSON method but does not return anything

let obj = {
  name:'zhangsan'.toJSON:function(){}}console.log(JSON.stringify(obj))  // undefined
Copy the code

If we serialize a Date, what is the result?

console.log(JSON.stringify(new Date()))  / / "act the T14:2020-06-20. 071 z"
Copy the code

You can see the output of this familiar time format because objects of type Date have their own implementation of toJSON

If an object’s attributes are not enumerable, they are filtered out

let obj = Object.create({},{
  name: {value:'zhangsan'.enumerable:false
  },
  age: {value:18.enumerable:true}})console.log(obj)  // {age: 18, name: "zhangsan"}
console.log(JSON.stringify(obj))  // {"age":18}
Copy the code

Second parameter

So far, we’ve given some examples of json.stringify (). A lot of people think this is the end of it, but it’s not, and now we have the second parameter.

Suppose you have an object that has a name, gender, age, and so on. But we don’t want to know anything about it, we just want to know what its name is. And its other attribute values are not as meaningless as those undefined values, how should we filter?

let obj = {
  name:'zhangsan'.gender:'female'.age:18.hobby:'swim'
}
console.log(JSON.stringify(obj,['age']))  // {"age":18}
Copy the code

This is where our second parameter comes in handy. We pass in an array, and the values in that array are the names of the properties that we want to keep, and anything that’s not in that array, don’t return. In addition to passing in an array type, we can also pass in a function.

let obj = {
  name:'zhangsan'.gender:undefined.age:18.hobby:'swim'
}
console.log(JSON.stringify(obj, (key, value) => {
  if(typeof value === 'string') {return undefined
  }
  return value
}))  // {"age":18}
Copy the code

In the function, we make some logical decisions to filter out property values if they are strings. Using this second parameter, we can also change the property value to undefined,symbol, etc., which would not otherwise be returned.

let obj = {
  name:'zhangsan'.gender:undefined.age:18.hobby:'swim'
}
console.log(JSON.stringify(obj, (key, value) => {
  if(typeof value === 'string') {return undefined
  }
  if(typeof value === 'undefined') {return 'not any more undefined'
  }
  return value
}))  // {"gender":"not any more undefined","age":18}
Copy the code

Using the toString() method, we can print the function’s contents:

let obj = {
  name:'zhangsan'.f:function(){
    console.log('I\'m a function')}}console.log(JSON.stringify(obj, (key, value) => {
  if(typeof value === 'function') {return Function.prototype.toString.call(value)
  }
  return value
})) 
// {"name":"zhangsan","f":"function(){\n console.log('I\\'m a function')\n }"}
Copy the code

The third parameter

Now that we have the second parameter, let’s talk about the third parameter. Yes, you read that right, it has a third parameter. The main purpose of this parameter is to beautify the output JSON string. In the absence of the third argument, the string we output is jammed together, making it hard to see. With it, we can format our output:

let obj = {
  name:'zhangsan'.age:18.gender:'female'
}
console.log(JSON.stringify(obj,null.2))  
/*{ "name": "zhangsan", "age": 18, "gender": "female" }*/
Copy the code

The third argument is passed a number of type n, which means that each level is indented by n more Spaces than its previous level, with n being at most 10. The third argument is passed a string of type, which is preceded by the string at most 10

let obj = {
  name:'zhangsan'.age:18.gender:'female'
}
console.log(JSON.stringify(obj,null.'😊'))  
/ * {😊 "name" : "zhangsan", 😊 "age" : 18, 😊 "gender" : "female"} * /
Copy the code

Summary: So far, we’ve basically covered the usage of json.stringify (). Most of the knowledge points are represented by the diagram below.