Formatters

JSON Compact Pretty-Print: Smart Formatting Between Minified and Expanded

Learn how smart JSON formatting works — keeping small objects on one line while expanding large ones. A practical guide to compact pretty-print techniques.

WebUtil Team

What Is Compact Pretty-Print?

Standard JSON formatters offer two modes: minified (everything on one line) or pretty-printed (everything expanded with indentation). Compact pretty-print (also called smart formatting) is a middle ground — small objects and arrays stay on one line while large structures are expanded. This preserves readability for shallow data while keeping deep structures navigable.

Python's json module doesn't support this natively, but you can achieve it with a custom encoder or by using tools that offer format/compact toggle options like our JSON Formatter. The key insight is that JSON readability is not binary — different data shapes benefit from different formatting strategies. A configuration object with three keys is perfectly readable on one line, while a list of 100 user records needs vertical space.

Compact formatting solves the problem that developers face daily: API responses that mix small metadata with large datasets. When you curl an endpoint and get back a wall of text, you toggle to pretty-print and suddenly a 10-line response becomes 300 lines. Compact formatting prevents this by being smart about what to expand and what to keep inline.

When to Use Compact Formatting

Compact formatting is ideal for log output where you need to see structure quickly without excessive line count. Development API responses become significantly more readable when small config objects stay inline but large data arrays are expanded for browsing. Configuration files benefit from compact formatting because it reduces vertical scrolling while preserving the structural understanding.

Debug output with mixed-depth data is where compact formatting truly shines. Consider a response containing a small metadata object alongside a large items array. In standard pretty-print, the metadata takes 15 lines for 3 keys. In compact mode, it takes 1 line. This difference compounds across hundreds of API calls during a debugging session.

Our JSON Formatter lets you toggle between expanded, compact, and minified views with one click. This means you can choose the right view for your task without switching tools. Compact mode is particularly useful when you need to share JSON snippets in documentation or chat messages where space is limited.

Implementing Compact Pretty-Print in Python

To implement compact formatting in Python, subclass json.JSONEncoder and override the encode method. Set a max_inline_length threshold (e.g., 80 characters) to determine what qualifies as compact. Use regex to detect small objects and arrays that can safely be inlined.

Here is the core approach: first serialize your data with standard pretty-print (indent=2). Then post-process the output with regular expressions. For objects: re.sub(r'\{([^}]+)\}', lambda m: '{' + m.group(1).strip() + '}' if len(m.group(0)) <= threshold else m.group(0), s). For arrays: re.sub(r'\[([^\]]+)\]', lambda m: '[' + m.group(1).strip() + ']' if len(m.group(0)) <= threshold else m.group(0), s).

The threshold determines the behavior: lower values produce more expanded output, higher values produce more compact output. A threshold of 80 characters works well for terminal-width output. For code documentation, you might want a tighter threshold of 60 characters to avoid horizontal scrolling. This approach requires no external dependencies and gives you fine-grained control over the formatting behavior.

Sponsored
Advertisement

Compact Formatting in Other Languages

JavaScript developers can achieve compact formatting by using JSON.stringify with a replacer function and post-processing the output with regex, similar to the Python approach. Node.js has the `json-stringify-pretty-compact` npm package that provides this behavior out of the box with customizable options including maxLength, indent, and arrayProcessor.

Go's encoding/json package doesn't support compact mode natively, but you can implement custom MarshalJSON methods on your structs. The approach is to marshal the struct normally, then run a post-processing step that inlines short values. Alternatively, you can use the jsonparser or ffjson libraries that give you more control over serialization.

Rust's serde_json library has both PrettyFormatter and CompactFormatter. You can write a custom formatter that switches between them based on the depth or size of the current value. This requires implementing the serde_json::ser::Formatter trait, which gives you hooks at every stage of serialization.

For developers who need compact formatting occasionally without writing code, our JSON Formatter is the fastest path. It supports all three modes — expanded, compact, and minified — with instant switching and no setup required.

Comparing JSON Formatting Modes

The three formatting modes serve different purposes and understanding their tradeoffs helps you choose the right one for each task. Minified mode removes all whitespace, producing the smallest possible output. This is ideal for API responses where bandwidth matters, for storing JSON in databases, and for machine-to-machine communication. A typical API response with 100 items is about 3KB minified.

Pretty-printed mode adds full indentation with each level getting its own line. This is the most readable format for humans browsing data structures. It makes nested relationships visually obvious and simplifies debugging. The same 100-item response is about 6KB pretty-printed — double the size of minified but far more readable.

Compact mode strikes the balance between the two. Structure is indented so you can see the hierarchy, but leaf nodes — small objects and arrays — stay on one line. For the same 100-item response, compact mode produces about 4KB. This is ideal for development workflows because it is readable enough to inspect at a glance while being compact enough to fit in terminal output and log files.

Try all three modes on our JSON Formatter to see which works best for your specific data. The right choice depends on your context: use minified for production APIs, pretty-printed for deep debugging, and compact for daily development work.

Use our free online tool to get started instantly.