JSON Stringify - The Optional Parameters

JSON Stringify - The Optional Parameters

We all use JSON.stringify() method for various reasons, but very few know about it's hidden optional parameters, and in this BitCode we will discover them with examples.

Table of contents

Normal Usage

Before we start, this is just a quick example of a normal usage, we can use it as reference/comparison to what's coming up next.

const user = {
  name: 'John',
  age: 20,
  isSingle: true,
}

const result = JSON.stringify(user)

console.log(result)
// Output: {"name":"John","age":20,"isSingle":true}

Whitelist Object's Properties

We can choose what properties we want to include in the stringified output by passing a list of string values that represents the whitelisted properties.

const user = {
  name: 'John',
  age: 20,
  isSingle: true,
}

const result = JSON.stringify(user, ['name'])

console.log(result)
// Output: {"name":"John"}

Replacer Function

We can also have a function to format our data before it's printed, the replacer function has two parameters, a key and a value (self-explanatory).
To demonstrate the power of the replacer function, we will add a password field to our user object, and to keep our users safe, we will replace the password value with a static one as follows:

const user = {
  name: 'John',
  age: 20,
  isSingle: true,
  password: 'super_sensitive_password' // Our new field
}

// Replacer function's name doesn't matter.
const replacer = (key, value) => {
    if (key === 'password') {
        return '****'
    }

	return value
}

const result = JSON.stringify(user, replacer)

console.log(result)
// Output: {"name":"John","age":20,"isSingle":true,"password":"****"}

Output Spacing

Finally, we can make our output more readable by passing a third argument to represent the amount of whitespace to be inserted (could be a string indentation/line break or a number for normal spacing).
Also, we don't have to pass a replacer function to insert some spacing, and this is exactly what we will do (we can pass either an undefined or a null to the second argument).

const user = {
  name: 'John',
  age: 20,
  isSingle: true,
}

const space = JSON.stringify(user, null, 2)

console.log(space)
/**
 * Output:
 * {
 *   "name": "John",
 *   "age": 20,
 *   "isSingle": true
 * }
 */

const indentation = JSON.stringify(user, null, '\t')

console.log(indentation)
/**
 * Output:
 * {
 *  	"name": "John",
 *  	"age": 20,
 *  	"isSingle": true
 * }
 */

Conclusion

At last, we discovered the lesser known parameters of the JSON.stringify() method.

As always, I hope you learned something.

Found this useful? feel free to share it with your friends.

Join the newsletter from to notify you of new posts and updates.

Like the post? consider buying us a coffee ❤️.