How to Format JSON in JavaScript: A Practical Guide

Published 2026-04-25 · Updated 2026-10-26 | About 2 min read

How to Format JSON in JavaScript: A Practical Guide

Format JavaScript data with JSON.stringify, handle common serialization limits, and choose between readable and compact JSON.

JavaScript's JSON methods are useful when debugging a response, writing a fixture, or saving configuration. This guide focuses on the built-in JSON.stringify method and explains what it can and cannot serialize.

JSON uses a strict data syntax. See RFC 8259 for the format definition; JavaScript object literals may contain constructs that are not valid JSON.

The Power of JSON.stringify() Parameters

Most developers are familiar with JSON.stringify(obj), but the function accepts value, replacer, and space. The space parameter controls indentation. See the MDN reference for JSON.stringify for its exact behavior and limits.

By passing a number (like 2) or a string (like \t), you tell JavaScript to add indentation and newlines to the output. For example: JSON.stringify(userData, null, 2) will produce a beautifully indented string that is easy for humans to read and audit during debugging.

Handling Circular References and BigInt

A common hurdle when formatting JSON is the 'Circular reference' error, which occurs when an object refers to itself. Standard JSON.stringify cannot handle these and will throw an error. In such cases, you may need a custom 'replacer' function or a library like flatted.

Additionally, native JSON does not support BigInt values. If your data contains large integers, you must convert them to strings within the replacer function: JSON.stringify(data, (key, value) => typeof value === 'bigint' ? value.toString() : value, 2). This ensures your formatting doesn't break when dealing with modern JavaScript data types.

Minification for Production Payloads

Omitting space produces compact JSON, while passing 2 produces readable indentation. Choose the representation appropriate for the consumer: source files and debugging often benefit from formatting, while APIs commonly send compact JSON and may use HTTP compression. Measure payload and response performance rather than assuming whitespace is the bottleneck.

Practical Example: Pretty-Printing to the Console

Next time you find yourself staring at [object Object] in your browser console, try wrapping your log in a formatter: console.log(JSON.stringify(myComplexObject, null, 2)). This simple change transforms a cryptic line into a searchable, readable tree structure that speeds up root-cause analysis.

Published by WebCodeveloper. Found an error or have a suggested correction? Contact us.

Continue Exploring

Continue with another guide or open a related tool.

Related Tools

Apply the concepts from this article with the linked tools below.