JSON.stringify()

JSON.stringify(value, replacer, space)
Returns: string · Added in vES5 · Updated March 14, 2026 · JSON
json serialization encoding

JSON.stringify() converts a JavaScript value into a JSON string. This is the standard way to serialize data for APIs, localStorage, or network transmission. The method handles objects, arrays, primitives, and special values like null and undefined.

Syntax

JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)

Parameters

ParameterTypeDefaultDescription
valueanyThe value to convert to a JSON string. Can be any valid JavaScript value including objects, arrays, strings, numbers, booleans, and null.
replacerfunction | array | nullnullA function that transforms the stringification process, or an array of strings and numbers specifying which properties to include. If null, all properties are included.
spacenumber | string | nullnullA number (1-10) of spaces for indentation, or a string to use as the indent. Makes the output readable.

The replacer Parameter

When replacer is a function, it receives two arguments: the key and the value being stringified. The function runs for the initial object too (with an empty string as key). Return values behave like this:

  • Return a number, string, boolean, or null — that value is used directly
  • Return undefined — the property is omitted from the output
  • Return any other object — it gets recursively stringified

When replacer is an array, only the properties whose names appear in the array are included. Symbol keys are always ignored.

The space Parameter

Pass a number to use that many spaces for indentation (clamped to a maximum of 10). Pass a string to use that string as the indent — only the first 10 characters are used. This makes debugging easier by producing human-readable output.

Examples

Basic Stringification

// Stringify an object
const user = { name: "Alice", age: 30 };
console.log(JSON.stringify(user));
// {"name":"Alice","age":30}

// Stringify an array
const nums = [1, 2, 3];
console.log(JSON.stringify(nums));
// [1,2,3]

// Stringify a primitive
console.log(JSON.stringify("hello"));
// "hello"

console.log(JSON.stringify(true));
// true

Using the replacer Function

const user = {
  name: "Alice",
  age: 30,
  password: "secret123",
  email: "alice@example.com"
};

// Remove sensitive fields
const safeJson = JSON.stringify(user, (key, value) => {
  if (key === "password") return undefined;
  return value;
});
console.log(safeJson);
// {"name":"Alice","age":30,"email":"alice@example.com"}

// Transform values
const data = { price: 19.99, tax: 1.50 };
const formatted = JSON.stringify(data, (key, value) => {
  if (typeof value === "number") return value.toFixed(2);
  return value;
});
console.log(formatted);
// {"price":"19.99","tax":"1.50"}

Using the space Parameter for Pretty Printing

const data = {
  name: "Alice",
  skills: ["JavaScript", "Python", "Rust"]
};

// 2-space indentation
console.log(JSON.stringify(data, null, 2));
// {
//   "name": "Alice",
//   "skills": [
//     "JavaScript",
//     "Python",
//     "Rust"
//   ]
// }

// Tab indentation
console.log(JSON.stringify(data, null, "\t"));
// {
// \t"name": "Alice",
// \t"skills": [
// \t\t"JavaScript",
// \t\t"Python",
// \t\t"Rust"
// \t]
// }

Handling Special Values

// null becomes "null"
console.log(JSON.stringify(null));
// null

// undefined is omitted
console.log(JSON.stringify({ a: 1, b: undefined, c: null }));
// {"a":1,"c":null}

// NaN and Infinity become null
console.log(JSON.stringify({ a: NaN, b: Infinity }));
// {"a":null,"b":null}

// Functions are omitted
console.log(JSON.stringify({ a: 1, fn: () => {} }));
// {"a":1}

// Arrays with undefined become null
console.log(JSON.stringify([1, undefined, 3]));
// [1,null,3]

Using toJSON for Custom Serialization

class User {
  constructor(name, password) {
    this.name = name;
    this.password = password;
  }

  toJSON() {
    return {
      name: this.name,
      // Don't include password in serialization
    };
  }
}

const user = new User("Alice", "secret123");
console.log(JSON.stringify(user));
// {"name":"Alice"}

Common Patterns

Storing Data in localStorage

const user = { name: "Alice", theme: "dark" };

// localStorage only stores strings
localStorage.setItem("user", JSON.stringify(user));

// Retrieve and parse
const stored = localStorage.getItem("user");
const parsed = stored ? JSON.parse(stored) : null;
console.log(parsed);
// { name: "Alice", theme: "dark" }

Sending Data to an API

const payload = {
  userId: 123,
  message: "Hello world",
  tags: ["greeting", "test"]
};

await fetch("/api/submit", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(payload)
});

Debugging with Pretty Print

const complex = {
  users: [
    { id: 1, name: "Alice", roles: ["admin", "user"] },
    { id: 2, name: "Bob", roles: ["user"] }
  ],
  metadata: { page: 1, total: 42 }
};

// Easy-to-read output for debugging
console.log(JSON.stringify(complex, null, 2));

Cloning Objects

const original = { a: 1, b: { c: 2 } };

// Create a deep clone
const clone = JSON.parse(JSON.stringify(original));

clone.b.c = 99;
console.log(original.b.c);
// 2 (original is unchanged)
console.log(clone.b.c);
// 99

Note: This only works for JSON-safe values. Functions, undefined, Symbol keys, and circular references are lost.

See Also

  • JSON.parse() — Parse a JSON string into a JavaScript value
  • BigInt — Handle integers beyond Number.MAX_SAFE_INTEGER