Skip to content

JSON.Stringify on second argument

Published: at 10:15 AM

In JavaScript, JSON.stringify() is a built-in method that converts a JavaScript value into a JSON string representation. JSON (JavaScript Object Notation) is a common format for exchanging data between web applications and APIs.

Here’s a breakdown of JSON.stringify():

Syntax:

JSON.stringify(value, replacer, space);

What it Does:

Examples:

const object = { name: "Alice", age: 30 };
const jsonString = JSON.stringify(object); // '{"name":"Alice","age":30}'

const array = [1, 2, 3];
const jsonString = JSON.stringify(array); // '[1,2,3]'

const date = new Date();
const jsonString = JSON.stringify(date); // '2024-02-07T02:54:22.394Z' (not recommended)

// Customizing with replacer:
const object = { name: "Alice", age: 30, password: "secret" };
const jsonString = JSON.stringify(object, (key, value) => {
  if (key === "password") return undefined; // Exclude password
  return value;
});

Let’s take a look another example, we have an array of objects and we want to get some specified properties and their value from the objects. For example given an Objects:

const objects = [
  { name: "Eka Prasetia" },
  { city: "Jakarta" },
  { hobby: "Play codes" },
];

Get some specified properties.

JSON.stringify(objects, ["name", "hobby"], 2);
// output "name" and "hobby" properties and their value

Another way, we can replace property value as follow.

const result = JSON.stringify(
  objects,
  (key, value) => {
    if (key.match(/name|city/)) return "👨‍👩‍👧✌";
    return value;
  },
  2
);
// output [{ "name": "👨‍👩‍👧✌"},{"city": "👨‍👩‍👧✌"},{"hobby": "Play codes"}]

The second argument is a replacer function, which is called for each property in the object being stringified. The replacer function can return a string or a number that will be used to replace the property’s value, or undefined if the property should be removed from the stringified output.

Key Points:

Thank you for reading this article, I hope you find it useful. Happy coding! 🔥