The Power of the JSON.stringify() replacer parameter

As previously detailed (2013 😱), you can use JSON.stringify()‘s second replacer parameter to pluck specific fields from it, by passing in an array:

var person = {"name":"Jim Cowart","location":{"city":{"name":"Chattanooga","population":167674},"state":{"name":"Tennessee","abbreviation":"TN","population":6403000}},"company":"appendTo"};

JSON.stringify(person, ["name", "company"], 4);
// ~> "{
//      "name": "Jim Cowart",
//      "company": "appendTo"
// }"

As Pawel explains the parameter can also be a function, to manipulate data before it is being returned. This comes in handy if you want to stringify a Set, for example:

const dude = {
  name: "Pawel",
  friends: new Set(["Dan", "Pedro", "Mr Gregory"])
};

const dudeStringified = JSON.stringify(dude, (key, value) =>
  value instanceof Set ? [...value] : value
);

console.log(dudeStringified);
// ~> {"name":"Pawel","friends":["Dan","Pedro","Mr Gregory"]}

The Power of the JSON.stringify() replacer parameter →

💡 Here’s a practicalu use-case: If your data object holds sensitive data, you can use the replacer to filter that part out:

const user = {
  name: 'Bramus',
  password: 'Azerty123',
};

JSON.stringify(user, (key, value) =>
    (key === 'password') ? 'XXXXXXXXXXXX' : value
);
// ~> "{"name":"Bramus","password":"XXXXXXXXXXXX"}"

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.