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]
const user = {
“name” : “Prateek Singh”,
“age” : 26
}
console.log(JSON.stringify(user));RESULT
// "{ "name" : "Prateek Singh", "age" : 26 }"


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”}]}
console.log(JSON.stringify(product,[‘name’]);//RESULT
{"name" : "Cake"}

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 }

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"}"

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