{}JSON FYI

JSON.stringify() in JavaScript — complete guide with examples

Master JSON.stringify(): the replacer, space parameter, toJSON(), and how to handle circular references, dates, and undefined values.

·7 min read

JSON.stringify() converts a JavaScript value into a JSON string. It is the standard way to serialize data before sending it to a server, writing to localStorage, or logging structured output.

Basic syntax

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

Simple examples

// Stringify an object
JSON.stringify({ name: "Ada", age: 30 });
// '{"name":"Ada","age":30}'

// Stringify an array
JSON.stringify([1, "two", true, null]);
// '[1,"two",true,null]'

// Stringify a primitive
JSON.stringify(42);    // '42'
JSON.stringify(true);  // 'true'
JSON.stringify(null);  // 'null'

Pretty-printing with the space parameter

Pass a number (indent size) or a string (custom indent character) as the third argument.

const obj = { id: 1, tags: ["json", "api"] };

JSON.stringify(obj, null, 2);
// {
//   "id": 1,
//   "tags": [
//     "json",
//     "api"
//   ]
// }

JSON.stringify(obj, null, '	'); // tab-indented

The replacer parameter

The replacer controls which properties are included. Pass an array to allowlist keys, or a function for full control.

const user = { id: 1, name: "Ada", password: "secret", role: "admin" };

// Array replacer — allowlist specific keys
JSON.stringify(user, ['id', 'name']);
// '{"id":1,"name":"Ada"}'

// Function replacer — transform or omit values
JSON.stringify(user, (key, value) => {
  if (key === 'password') return undefined; // omit
  if (typeof value === 'string') return value.toUpperCase();
  return value;
});
// '{"id":1,"NAME":"ADA","ROLE":"ADMIN"}'

What JSON.stringify omits

Several JavaScript value types are not valid JSON and are silently dropped or converted:

const obj = {
  name: "Ada",
  greet: () => "hello",  // functions → omitted
  sym: Symbol("x"),      // symbols → omitted
  x: undefined,          // undefined → omitted
  score: NaN,            // NaN → null
  ratio: Infinity,       // Infinity → null
  now: new Date(),       // Date → ISO string
};

JSON.stringify(obj);
// '{"name":"Ada","score":null,"ratio":null,"now":"2026-04-27T..."}'

Customising serialization with toJSON()

Add a toJSON() method to any object and JSON.stringify will call it to get the serialised value.

class Money {
  constructor(amount, currency) {
    this.amount = amount;
    this.currency = currency;
  }
  toJSON() {
    return `${this.amount} ${this.currency}`;
  }
}

JSON.stringify(new Money(9.99, 'USD')); // '"9.99 USD"'

Handling circular references

// JSON.stringify throws on circular structures:
const a = {};
a.self = a;
JSON.stringify(a); // TypeError: Converting circular structure to JSON

// Fix: use a replacer that tracks seen objects
function safeStringify(obj) {
  const seen = new WeakSet();
  return JSON.stringify(obj, (key, value) => {
    if (typeof value === 'object' && value !== null) {
      if (seen.has(value)) return '[Circular]';
      seen.add(value);
    }
    return value;
  });
}

Sending JSON to a server

await fetch('/api/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Ada', role: 'engineer' }),
});

Paste your JSON into the validator →

Get the exact line, column, and a fix hint in seconds — no upload, no signup.

Open JSON Validator →

Frequently asked questions

Does JSON.stringify sort keys?+

No, not by default. Key order follows insertion order (for string keys). Pass a replacer function that returns keys in your desired order, or sort the object before stringifying.

Why does JSON.stringify(undefined) return undefined (not a string)?+

undefined is not a valid JSON value, so JSON.stringify returns the JavaScript value undefined — not the string 'undefined'. This is also why undefined properties are silently omitted from objects.

How do I pretty-print JSON in the browser console?+

Use console.log(JSON.stringify(obj, null, 2)) for a formatted string, or just console.log(obj) — the browser DevTools render objects interactively without needing stringify.

What is the maximum safe size for JSON.stringify?+

Depends on the JS engine's maximum string length (typically ~1 GB in V8). In practice, performance degrades above a few megabytes. Very large datasets should use streaming serialisers.

Related tools & guides