JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JSON.stringify()

15 April 2025 | Category:

The JSON.stringify() method is used to convert a JavaScript object or array into a JSON-formatted string.

âś… In simple words:
JavaScript object → JSON string


📦 Syntax

JSON.stringify(value[, replacer[, space]]);

Parameters:

  • value: The JavaScript value you want to convert.
  • replacer (optional): A function or array to filter properties.
  • space (optional): A number or string for pretty-printing (indentation).

âś… Example 1: Convert Object to JSON String

const user = {
  name: "Alice",
  age: 25,
  isStudent: false
};

const jsonStr = JSON.stringify(user);

console.log(jsonStr);
// Output: {"name":"Alice","age":25,"isStudent":false}

âś… Example 2: Convert Array to JSON String

const fruits = ["apple", "banana", "mango"];

const jsonFruits = JSON.stringify(fruits);

console.log(jsonFruits);
// Output: ["apple","banana","mango"]

🎨 Example 3: Pretty Print with Indentation

const user = { name: "Bob", age: 30 };

const formattedJson = JSON.stringify(user, null, 2);

console.log(formattedJson);
/*
Output:
{
  "name": "Bob",
  "age": 30
}
*/

đź§  Optional: Using replacer to Filter Properties

You can control which properties to include:

🔹 Using an array:

const person = { name: "Alice", age: 25, city: "Delhi" };

const filtered = JSON.stringify(person, ["name", "city"]);

console.log(filtered);
// Output: {"name":"Alice","city":"Delhi"}

🔹 Using a function:

const person = { name: "Alice", age: 25, city: "Delhi" };

const custom = JSON.stringify(person, (key, value) => {
  if (typeof value === "number") return undefined;
  return value;
});

console.log(custom);
// Output: {"name":"Alice","city":"Delhi"}

⚠️ Important Notes

  • JSON.stringify() doesn’t include undefined, functions, or symbols.
  • Circular references (objects referring to themselves) will cause an error.

âś… Summary

FeatureDescription
ConvertsJavaScript value → JSON string
Used inAPIs, localStorage, data saving
Optional Parametersreplacer, space for customization
Pretty PrintingUse space parameter for readable output