jsondecode.com logo

HomeChevronBlogChevronJSON.stringify() Complete Guide: Options, Replacer, and Space Parameter

Blog post

JSON.stringify() Complete Guide: Options, Replacer, and Space Parameter

Master JSON.stringify() in JavaScript — replacer functions, space parameter for pretty-printing, handling undefined/circular references, and performance tips.

author

Shashank Jain

Author

22/05/20260 minutes 51 seconds read
JSON.stringify() Complete Guide: Options, Replacer, and Space ParameterJSON.stringify() Complete Guide: Options, Replacer, and Space Parameter

Article

What is JSON.stringify()?

JSON.stringify() converts a JavaScript value to a JSON string. It is the primary way to serialize objects for APIs, local storage, and logging.

Basic Syntax

JSON.stringify(value, replacer, space)
  • value — the value to serialize
  • replacer — optional function or array to filter/transform keys
  • space — optional indentation (number of spaces or string)

Pretty-Printing with the Space Parameter

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

Filtering Keys with a Replacer Array

const user = { id: 1, name: 'Alice', password: 'secret' };
JSON.stringify(user, ['id', 'name']);
// '{"id":1,"name":"Alice"}'  — password excluded

Transforming Values with a Replacer Function

JSON.stringify(data, (key, value) => {
  if (value === undefined) return null; // preserve undefined as null
  if (typeof value === 'bigint') return value.toString();
  return value;
});

What JSON.stringify() Silently Drops

ValueIn objectIn array
undefinedKey droppedBecomes null
functionKey droppedBecomes null
SymbolKey droppedBecomes null
NaN / InfinityBecomes nullBecomes null

Handling Circular References

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;
  });
}

Use the JSON formatter at jsondecode.com to validate and pretty-print your JSON output.

Keep reading

Recent blogs

View all

If jsondecode.com saved you time, share it with your team

Free forever. No ads. No sign-up. Help other developers find it.