JSON.stringify() with replacer

ES5+

Uses a replacer function to filter or transform values during JSON stringification.

Syntax

JSON.stringify(value, replacer)

Parameters

value any

The value to convert to a JSON string

replacer Function

A function that receives key and value, and returns the replacement value

Return Value

string

A JSON string with transformed values

Examples

JavaScript
const obj = {
  name: 'John',
  password: 'secret123',
  age: 30
};
const result = JSON.stringify(obj, (key, value) => {
  if (key === 'password') return undefined;
  return value;
});
console.log(result);
Output:
// '{"name":"John","age":30}'

📌 When to Use

Use a replacer function when you need to transform values during stringification, such as filtering sensitive data, converting custom types, or handling circular references.

⚠️ Common Mistakes

Returning undefined from the replacer removes the property entirely, which may not be the intended behavior.

✅ Best Practices

Use a replacer function for complex transformations and a replacer array for simple property filtering.

⚡ Performance Notes

The replacer function is called for every property, so keep it simple for large objects. Consider pre-processing data instead of using complex replacers.

🌍 Real World Example

Logging Sanitizer

Sanitize objects for logging by removing sensitive data and truncating long strings.

function sanitizeForLogging(obj) {
  const sensitivePatterns = /password|secret|token|key|auth/i;
  const maxStringLength = 100;

  const replacer = (key, value) => {
    if (sensitivePatterns.test(key)) {
      return '[HIDDEN]';
    }
    if (typeof value === 'string' && value.length > maxStringLength) {
      return value.substring(0, maxStringLength) + '... [truncated]';
    }
    return value;
  };

  return JSON.stringify(obj, replacer, 2);
}

const request = {
  url: '/api/users',
  body: { password: 'secret123' },
  longField: 'a'.repeat(200)
};

console.log(sanitizeForLogging(request));

Related Methods