Published on

Selecting or Filtering Keys in JSON.stringify

Authors

Sometimes, we get might want to serialize only the keys that we want using JSON.stringify() and avoid including everything in an object. It could be because of trying to reduce payload size or to improve security or privacy.

Here is how to do it:

JSON.stringify has three parameters

  • value -> The object that you want to convert to a string.
  • replacer (optional) -> An array of keys or a replacer function used to create the resulting JSON string.
  • space (optional) -> Used to insert white space

We'll be using the replacer function for our use case.

We can include the needed keys in the resulting JSON string by passing an array of keys or a replacer function to the replacer parameter

const user = {
    name:"Ashik Nesin",
    password:"Qwerty123"
}

JSON.stringify(user) // '{"name":"Ashik Nesin","password":"Qwerty123"}'

JSON.stringify(user,['name']) // '{"name":"Ashik Nesin"}'


JSON.stringify(user,['name']) // '{"name":"Ashik Nesin"}'

function replacer(key, value) {
  // Filtering out properties
  if (key === "password") {
    return undefined;
  }
  return value;
}

JSON.stringify(user,replacer)  // '{"name":"Ashik Nesin"}'

Happy filtering keys!