Hiprup

What is JSON.stringify with replacer and space?

JSON.stringify takes two optional extra arguments that control the output.

  • replacer — a function or array of keys that filters or transforms which properties are included.

  • space — adds indentation for readable, pretty-printed JSON (e.g. 2 spaces).

Common uses: pretty-print for logs/files, or strip sensitive fields like passwords before serialising.

const user = { name: 'John', password: 'secret', age: 30, role: 'admin' };

// Basic
console.log(JSON.stringify(user));
// '{"name":"John","password":"secret","age":30,"role":"admin"}'

// With space (pretty print)
console.log(JSON.stringify(user, null, 2));
// {
//   "name": "John",
//   "password": "secret",
//   ...
// }

// Replacer function (filter sensitive data)
const safe = JSON.stringify(user, (key, value) => {
  if (key === 'password') return undefined; // Exclude
  return value;
}, 2);
// { "name": "John", "age": 30, "role": "admin" }

// Replacer array (whitelist properties)
console.log(JSON.stringify(user, ['name', 'age']));
// '{"name":"John","age":30}'

// Custom toJSON method
class User {
  constructor(name, password) {
    this.name = name;
    this.password = password;
  }
  toJSON() {
    return { name: this.name }; // Exclude password
  }
}

Replacer function: return undefined to exclude a property (password filtering). Replacer array: whitelist of property names. space: 2 adds 2-space indentation. toJSON method on a class controls how instances are serialized.

All three enable controlled, safe serialization.

The replacer for filtering sensitive data (passwords) is the most practical use case. The array replacer for whitelisting properties is simpler. toJSON for class-level control. space: 2 for readable output (logging/debugging).

Know what JSON.stringify cannot handle: functions, undefined, Symbol, circular references.

What is JSON.stringify with replacer and space? | Hiprup