JSON.Stringify on second argument
Source: Dev.to
Syntax
JSON.stringify(value, replacer, space);
- value – The JavaScript value to be converted (object, array, string, number, etc.).
- replacer (optional) – A function or array that transforms the value before stringification.
- space (optional) – A string (or number) used to indent the output for readability.
What it Does
- Converts primitive values like strings, numbers, booleans, and
nulldirectly to their JSON equivalents. - Converts arrays by iterating through their elements and stringifying each one.
- Converts objects by enumerating their properties and stringifying their key‑value pairs.
- Excludes properties with
undefinedvalues or functions by default. - Can be customized with the
replacerandspaceoptions.
Examples
Basic usage
const object = { name: "Alice", age: 30 };
JSON.stringify(object); // '{"name":"Alice","age":30}'
const array = [1, 2, 3];
JSON.stringify(array); // '[1,2,3]'
const date = new Date();
JSON.stringify(date); // '"2024-02-07T02:54:22.394Z"' (not recommended)
Using a replacer function to exclude a property
const object = { name: "Alice", age: 30, password: "secret" };
const jsonString = JSON.stringify(object, (key, value) => {
if (key === "password") return undefined; // Exclude password
return value;
});
// '{"name":"Alice","age":30}'
Filtering properties with a replacer array
const objects = [
{ name: "Eka Prasetia" },
{ city: "Jakarta" },
{ hobby: "Play codes" },
];
JSON.stringify(objects, ["name", "hobby"], 2);
// [
// {
// "name": "Eka Prasetia"
// },
// {},
// {
// "hobby": "Play codes"
// }
// ]
Replacing property values with a replacer function
const result = JSON.stringify(
objects,
(key, value) => {
if (key.match(/name|city/)) return "👨👩👧✌";
return value;
},
2
);
// [
// {
// "name": "👨👩👧✌"
// },
// {
// "city": "👨👩👧✌"
// },
// {
// "hobby": "Play codes"
// }
// ]
The second argument (replacer) can be a function that is called for each property. It may return a new value (string, number, etc.) to replace the original, or undefined to omit the property from the output.
Key Points
JSON.stringify()is useful for sending data to servers or storing it in local storage.- Be mindful of circular references or functions when stringifying objects.
- Use a
replacerto customize the output or exclude sensitive information. - Avoid stringifying
Dateobjects directly, as JSON has no native date type.
Happy coding! 🔥