• 5 Secret Features of json.stringify ()
  • Original post by Prateek Singh
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: zoomdong
  • Proofread by: Long Xiong, Niayyy

Five secret features of json.stringify ()

The json.stringify () method converts a JavaScript object or value to a JSON string.

As a JavaScript developer, json.stringify () is the most common function used for debugging. But what does it do? Couldn’t we use console.log() to do the same thing? Let’s have a try.

// Initialize a user object
const user = {
 "name" : "Prateek Singh"."age" : 26
}

console.log(user);

/ / the result
// [object Object]
Copy the code

Oh! Console.log () did not help us print the results we expected. It prints **[object object]** because the default conversion from object to string is [Object object]. Therefore, we use json.stringify () to first convert the object to a string and then print it in the console, as shown below.

const user = {
 "name" : "Prateek Singh"."age" : 26
}

console.log(JSON.stringify(user));

/ / the result
// "{ "name" : "Prateek Singh", "age" : 26 }"
Copy the code

In general, it is common for developers to use the Stringify function, as we did above. But I’m going to let you in on some hidden secrets that will make your development a lot easier.

1: Second argument (array)

Yes, the stringify function can also take a second argument. It is an array of keys for objects to print in the console. Looks simple? Let’s dig a little deeper. We have an object called product and we want to know the value of the name property of product. When we print it out: console.log(json.stringify (product)); It will print the following result.

{"id":"0001"."type":"donut"."name":"Cake"."ppu":0.55."batters": {"batter": [{"id":"1001"."type":"Regular"}, {"id":"1002"."type":"Chocolate"}, {"id":"1003"."type":"Blueberry"}, {"id":"1004"."type":"The Devil 's Food"}},"topping": [{"id":"5001"."type":"None"}, {"id":"5002"."type":"Glazed"}, {"id":"5005"."type":"Sugar"}, {"id":"5007"."type":"Powdered Sugar"}, {"id":"5006"."type":"Chocolate with Sprinkles"}, {"id":"5003"."type":"Chocolate"}, {"id":"5004"."type":"Maple"}}]Copy the code

The name key is hard to find in the logs because the console displays a lot of useless information. As the object gets larger, it becomes more difficult to find properties. The second argument to the stringify function is useful here. Let’s rewrite the code and see the results.

console.log(JSON.stringify(product,['name' ]);

/ / the result
{"name" : "Cake"}
Copy the code

That solves the problem. Instead of printing the entire JSON object, we can print only the desired properties by passing the desired keys as an array in the second argument.

2: The second argument (function)

We can also pass in a function as a second argument. It evaluates each key-value pair based on the logic written in the function. If undefined is returned, no key-value pairs are printed. Please refer to examples for a better understanding.

const user = {
 "name" : "Prateek Singh"."age" : 26
}
Copy the code

/ / the result
{ "age" : 26 }
Copy the code

Only age is printed because the function returns undefined if typeOf is a String.

3: The third parameter is a number

The third argument controls the spacing of the last string. If the argument is a number, each level in stringification will indent that number of space characters.

// Note: '--' is used instead of Spaces for comprehension purposes

JSON.stringify(user, null.2);
/ / {
//--"name": "Prateek Singh",
//--"age": 26,
//--"country": "India"
/ /}
Copy the code

4: The third argument is a string

If the third argument is string, it will be used instead of the space character shown above.

JSON.stringify(user, null.'* *');
/ / {
//**"name": "Prateek Singh",
//**"age": 26,
//**"country": "India"
/ /}
// * replaces the space character
Copy the code

5: toJSON method

We have a method called toJSON that can be a property of any object. Json.stringify returns the result of this function and serializes it, rather than converting the entire object to a string. See the example below.

const user = {
 firstName : "Prateek".lastName : "Singh".age : 26,
 toJSON() {
    return { 
      fullName: `The ${this.firstName} + The ${this.lastName}`}; }}console.log(JSON.stringify(user));

/ / the result
// "{ "fullName" : "Prateek Singh"}"
Copy the code

Here we can see that it prints only the result of the toJSON function, not the whole object.

I hope you’ve learned some basic features of Stringify ().

If you find this article useful, please give it a thumbs up and read with me more wonderful articles like this one.

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.