JSON Stringify in JavaScript

JSON.stringify() is a built-in JavaScript method that stringify JS objects or values into JSON strings. It enables structured data serialization for storage, transmission, or API communication. To effectively work with JSON in JavaScript, every developer must know how to transform objects into valid JSON text.

In this tutorial, you will learn how to use JavaScript’s JSON.stringify() method to serialize objects into JSON strings. We will cover its syntax, parameters, practical examples, and how to handle exceptions such as circular references.

What is JSON Stringify and Serialization?

JSON.stringify() is a JavaScript method used to serialize data. Serialization means converting JavaScript values such as objects, arrays, or primitives into a JSON string format that can be stored or transmitted.

  • Transforms JavaScript data into JSON strings for APIs, storage, or communication.
  • Converts in-memory values into a platform-independent string representation.
  • Supports customization using replacer and space parameters.
  • Handles nested structures and arrays of objects reliably.

Converting an Object to a JSON String

Suppose you have a JavaScript object like this:

JavaScript Object

Copy
const user = { name: "Alice", age: 30, isAdmin: false };

After serialization using JSON.stringify() function, it becomes:

JSON String Output

Copy
{"name":"Alice","age":30,"isAdmin":false}

Serialization Logic Explained

This method processes JavaScript data and returns a JSON-formatted string based on specific rules and optional parameters.

  • Converts JavaScript values like objects, arrays, or primitives into a JSON string.
  • Applies the optional replacer to filter or transform properties during serialization.
  • Uses the space argument to add indentation and make the output more readable.
  • Calls an object's toJSON() method if defined to customize its serialized result.

Using JSON.stringify() in JavaScript

Syntax

JSON.stringify() Syntax

Copy
const jsonString = JSON.stringify(value, replacer, space);

Parameters

The JSON.stringify() method accepts three parameters:

Parameter Description
value The JavaScript value (object, array, primitive) to serialize
replacer (Optional) A function or array that filters or transforms properties before stringification
space (Optional) A number or string that adds indentation and line breaks for readability

How to Stringify a JavaScript Object to a JSON String?

Basic Example

// Serialize a simple object
const user = { name: "Alice", age: 30, isAdmin: false };
const jsonString = JSON.stringify(user);
  • user is a JavaScript object
  • JSON.stringify(user) converts it into a compact JSON string

JSON.parse() vs JSON.stringify()

  • JSON.parse() decodes a JSON string → JavaScript value
  • JSON.stringify() encodes a JavaScript value → JSON string

JSON.parse() Example

Copy
const jsonText = '{"user":"Bob","active":true}';
const jsObject = JSON.parse(jsonText);
console.log(jsObject); // { user: "Bob", active: true }

Advanced JSON.stringify() Scenarios

Stringifying Arrays with JSON.stringify()

You can easily convert JavaScript arrays into JSON strings using JSON.stringify().

Array Example

// Serialize a simple array
const fruits = ["apple", "banana", "cherry"];
const jsonString = JSON.stringify(fruits);
  • fruits is a JavaScript array of strings
  • JSON.stringify(fruits) returns a JSON-formatted array string

Using the Replacer Function

The replacer parameter allows you to exclude or modify data during serialization:

Replacer Example

const user = { name: "Alice", age: 30, password: "secret" };
const jsonString = JSON.stringify(user, (key, value) => {
  if (key === "password") return undefined;
  return value;
});
  • The replacer function omits the password property
  • Ideal for removing sensitive information before sending data

Another advanced example using a custom replacer function:

Advanced Replacer Example

const user = { name: "Alice", age: 30, password: "secret123", email: "alice@example.com", city: null };
const replacer = (key, value) => {
  if (key === "password") return undefined;
  if (key === "email") return value.replace(/(.+)@/, "***@");
  if (typeof value === "string") return value.toUpperCase();
  if (value === null) return undefined;
  return value;
};
const jsonString = JSON.stringify(user, replacer, 2);
  • Removes password and null fields from the output
  • Masks email and converts all string values to uppercase
  • Demonstrates how to manipulate data during serialization

Did you know?

You can also pass an array to replacer to include only specific keys: JSON.stringify(user, ["name","age"]).

Pretty-Printing JSON With Space Parameter

Use the space parameter for readable output:

Pretty-Print Example

const user = { name: "Alice", age: 30, email: "alice@example.com", isAdmin: false };
const jsonString = JSON.stringify(user, null, 2);
  • The space parameter formats JSON with indentation, improving readability.
  • You can pass a number (e.g., 2) to specify how many spaces to use per level.
  • It is useful when displaying JSON output in a UI or logging for debugging purposes.

Handling Circular References

A circular reference occurs when an object directly or indirectly refers to itself, creating an infinite loop in the structure.

If an object contains circular references, JSON.stringify() will throw a TypeError. You must handle them explicitly.

Circular Reference Example

const employee = { name: "John" };
const department = { title: "Engineering", lead: employee };
employee.department = department; // circular reference

try {
  JSON.stringify(employee);
} catch (e) {
  console.log("Error:", e.message); // TypeError: Converting circular structure to JSON
}
  • The object employee has a nested reference to department.
  • That department in turn holds a reference back to the employee object.
  • This mutual reference creates a circular structure.
  • The JSON.stringify() method cannot serialize such structures and throws an error.

Note:

JSON.stringify() throws an error if it encounters a circular reference. Use custom serialization logic or libraries like flatted to handle such cases.

Stringify Date Object

The JSON.stringify() function automatically converts JavaScript Date objects into ISO 8601 string format.

Date Serialization Example

const today = new Date("2025-08-03");
const jsonDate = JSON.stringify(today);
  • Date objects are not stored as date types in JSON, only their string form is kept.
  • The resulting string is always in standardized ISO format.
  • To restore it, you will need to use new Date(jsonDate) manually when using JSON.parse() method.

Stringify Functions

The JSON.stringify() method ignores functions during serialization, removing any key-value pair where the value is a function.

Function Serialization Example

const obj = {
  name: "Widget",
  calculate: function () {
    return 42;
  }
};
const json = JSON.stringify(obj);

Custom Serialization Using toJSON() Method

  • The toJSON() is a built-in method for types like Date in JavaScript.
  • You can define your own toJSON() method in custom objects.
  • When present, JSON.stringify() automatically calls toJSON() during serialization.
  • The return value of toJSON() replaces the original object in the resulting JSON string.
  • It is useful for customizing output in place of unsupported types like functions.

Stringify Using toJSON()

const product = {
	id: 101,
	name: "Gadget",
	price: 199.99,
	toJSON() {
		return {
			id: this.id,
			name: this.name
		};
	}
};
  • toJSON() lets you define exactly what gets serialized from an object.
  • This is useful for transforming or filtering data before serialization.
  • It overrides both the default behavior and any replacer function for that object.
  • Properties not returned from toJSON() (like price here) will be excluded from the final JSON string.

Best Practices for JSON.stringify()

When Not to Use JSON.stringify()

  • When dealing with circular references without custom logic.
  • If you need to preserve functions or complex class instances.
  • When performance is critical in large data pipelines without streaming.

Tip:

The toJSON() method is commonly used in Date, RegExp, and custom classes to control serialization output.

Performance Tips

  • Cache serialized results if reused frequently to avoid redundant conversions.
  • Omit the space argument in production to reduce JSON size.
  • Use streaming or chunked serialization for very large data sets.

Security Considerations

  • Use a replacer function to exclude or mask sensitive data.
  • Never serialize functions or objects containing executable code.
  • Always combine JSON.stringify() with JSON.parse() function cautiously to prevent injection risks.