JSON.stringify()

ES5+

Converts a JavaScript value to a JSON string.

Syntax

JSON.stringify(value, replacer, space)

Parameters

value any

The value to convert to a JSON string

replacer Function | Array optional

A function that alters the behavior of the stringification process, or an array of property names to include

space number | string optional

A string or number used to insert white space into the output JSON string for readability

Return Value

string

A JSON string representing the given value

Examples

JavaScript
const obj = { name: 'John', age: 30 };
console.log(JSON.stringify(obj));
Output:
// '{"name":"John","age":30}'

📌 When to Use

Use JSON.stringify() when sending data to APIs, storing objects in localStorage, creating deep copies of plain objects, or debugging by logging objects.

⚠️ Common Mistakes

Attempting to stringify objects with circular references throws an error.

Functions, undefined, and Symbols are silently omitted from the output.

Date objects are converted to ISO strings, not preserved as Date instances.

✅ Best Practices

Use the replacer to filter sensitive data like passwords before sending to logs or APIs.

Use the space parameter (2 or 4) for readable debug output, but omit it for production data transfer.

⚡ Performance Notes

JSON.stringify() is optimized but can be slow for very large objects. The space parameter adds overhead. For high-frequency serialization, consider caching or using Web Workers.

🌍 Real World Example

Secure Data Serializer

Serialize objects while filtering out sensitive fields and handling special types.

function secureStringify(obj, options = {}) {
  const { sensitiveKeys = ['password', 'token', 'secret'], pretty = false } = options;

  const replacer = (key, value) => {
    // Filter sensitive keys
    if (sensitiveKeys.includes(key.toLowerCase())) {
      return '[REDACTED]';
    }
    // Handle BigInt
    if (typeof value === 'bigint') {
      return value.toString() + 'n';
    }
    return value;
  };

  return JSON.stringify(obj, replacer, pretty ? 2 : undefined);
}

const userData = {
  name: 'John',
  email: 'john@example.com',
  password: 'secret123',
  apiToken: 'abc123xyz'
};

console.log(secureStringify(userData, { pretty: true }));
// { "name": "John", "email": "john@example.com", "password": "[REDACTED]", "apiToken": "[REDACTED]" }

Related Methods