5 Secret features of JSON.stringify()

Prateek Singh
Feb 14 · 3 min read
Credits: Kirmeli.com

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

Being a JavaScript developer, JSON.stringify() is the most common functions used for debugging. But what is the use of this, can’t we use our friend console.log() alone for the same? Let’s give it a try.

//Initialize a User object
const user = {
“name” : “Prateek Singh”,
“age” : 26
}
console.log(user);RESULT
// [object Object]

Oops! console.log() didn’t help us print the desired result. It prints [object Object] because the default conversion from an object to string is “[object Object]”. So we use JSON.stringify() to first convert the object into a string and then print in the console, like this.

const user = {
“name” : “Prateek Singh”,
“age” : 26
}
console.log(JSON.stringify(user));RESULT
// "{ "name" : "Prateek Singh", "age" : 26 }"

Generally, developers use this stringify function in a simple way as we did above. But I am gonna tell you some hidden secrets of this little gem which will make your life easy.

1: The second argument (Array)

Yes, our stringify function can have a 2nd argument also. It’s an array of keys to the object which you want to print in the console. Look simple? Let’s take a closer look. We have an object product & we want to know the name of the product. When when we print it as:
console.log(JSON.stringify(product));
it gives the below 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”:”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”}]}

It is difficult to find the name key in the log as there is a lot of useless info displayed on the console. When the object grows bigger, difficulty increases.
The 2nd argument of stringify function comes into the rescue. Let’s rewrite the code again & see the result.

console.log(JSON.stringify(product,[‘name’]);//RESULT
{"name" : "Cake"}

Problem solved, instead of printing the whole JSON object we can print only the required key by passing it as an array in the 2nd argument.

2: The second argument (Function)

We can also pass a 2nd argument as a function. It evaluates each key-value pair according to the logic written in the function. If you return undefined the key-value pair will not print. See this example for a better understanding.

const user = {
“name” : “Prateek Singh”,
“age” : 26
}
Passing function as 2nd argument
// Result
{ "age" : 26 }

Only age is printed as our function condition return undefined for the value typeOf String.

3: The third argument as Number

The third argument controls the spacing in the final string. If the argument is a number, each level in the stringification will be indented with this number of space characters.

Note: '--' represnts the spacing for understanding purposeJSON.stringify(user, null, 2);
//{
//--"name": "Prateek Singh",
//--"age": 26,
//--"country": "India"
//}

4: The third argument as String

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

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

5: The toJSON method

We have one method named toJSON which can be a part of any object as its property. JSON.stringify returns the result of this function and stringifies it instead of converting the whole object into the string. See this example.

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

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

I hope you learned some owsmm features of our little friend stringify() .

If you find this article useful, please hit the ‘clap’ button and follow me with more exciting articles like this.

Thanks For Reading

Happy Coding || Write 2 Learn

JavaScript in Plain English

Learn the web's most important programming language.

Prateek Singh

Written by

Talk is Cheap… SHOW ME THE CODE.

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade