Beyond Basics: Unlocking 5 Lesser-Known Powers of JSON.stringify()

Discover the Unseen Capabilities of JSON.stringify() and Become a JavaScript Wizard in No Time.

As a JavaScript developer, you’re likely familiar with JSON.stringify() method, commonly used for debugging. But why resort to this when console.log() seems sufficient? Let’s delve into its utility.

Consider a superhero object:

const superhero = {
name:'Bhagat Singh',
age:21
};
console.log(superhero.toString()); // Result: [object Object]

Unfortunately, console.log() disappoints, displaying “[object Object]” as the default conversion from an object to a string. Enter JSON.stringify():

const superhero = {
name:'Bhagat Singh',
age:21
};
console.log(JSON.stringify(superhero, ['name']));
// Result: {"name":"Bhagat Singh","age":21}

While most developers use JSON.stringify() in a straightforward manner, I’m about to unveil some hidden secrets that will simplify your life.

1. The Second Argument (Array)

- Did you know JSON.stringify() accepts a second argument? It’s an array of keys from the object that you want to display in the console. For instance:

const superhero = {
name:'Bhagat Singh',
age:21
};
console.log(JSON.stringify(superhero, ['name']));
// Result: {"name": "Bhagat Singh"}

Instead of cluttering the console with the entire JSON object, selectively print the desired key by passing it as an array in the second argument.

2. The Second Argument (Function)

  • The second argument can also be a function, evaluating each key-value pair based on the logic within.
  • If undefined is returned, then then key-value pair won’t be printed.
const superhero = {
name:'Bhagat Singh',
age:21
};

console.log(JSON.stringify(superhero, (key, value) => (key === "age" ? value : undefined)));
// Result: {"age": 21}

3. The Third Argument as Number

- The third argument controls spacing in the final string. If it’s a number, each level in the stringification will be indented accordingly.

const superhero = {
name:'Bhagat Singh',
age:21
};


console.log(JSON.stringify(superhero, null, 2));
Output of different spacing

4. The Third Argument as String

  • Alternatively, if the third argument is a string, it replaces the space character.

5. The toJSON Method

Objects can have a toJSON method.

JSON.stringify() returns the result of this function and stringifies it instead of converting the entire object.

const superhero= {
firstName: "Bhagat",
lastName: "Singh",
age: 21,
toJSON() {
return {
fullName: `${this.firstName} + ${this.lastName}`
};
}
};

console.log(JSON.stringify(superhero));
// Result: "{ "fullName" : "Bhagat Singh"}"

Explore these powerful features of JSON.stringify() and make your coding journey even more efficient!

--

--

राहुल मिश्रा
राहुल मिश्रा

Responses (4)