PHPnews.io

The Power of the JSON.stringify() replacer parameter

Written by Bram.us / Original link on Dec. 2, 2019

javascript-logo-banner.jpg

As previously detailed (2013 1f631.png), 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 →

1f4a1.png If your data object holds sensitive data, you can use the replacer to filter that data out:

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

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

tutorialzine calevans elsewhere link bram

« Passing Elements as Props in React - Manage React State with zustand »