keepcalculator

06 Numbers and Powers

Print JSON Pretty Python: Formatting Guide

Card No. 06·55554 · Updated · Standard formula, shown below

To print JSON in a readable, indented format in Python, use the json.dumps() function with the indent parameter. For example, print(json.dumps(data, indent=2)) outputs your JSON object with two spaces of indentation per level, making it easy to read and debug.

Why Pretty-Print JSON?

Pretty-printing is essential for debugging and logging. Raw JSON is compact and hard to read, especially with deeply nested structures. Indentation reveals the hierarchy at a glance, making it easier to spot missing commas, mismatched brackets, or unexpected nesting. It also helps when sharing JSON in documentation or code reviews, where readability matters.

How to Use json.dumps() Effectively

Beyond indent, there are several parameters that enhance output:

  • sort_keys=True – sorts dictionary keys alphabetically, which is useful for consistent output and diffing.
  • separators=(',', ': ') – customizes the separators. For compact output, use (',', ':') to remove spaces.
  • ensure_ascii=False – keeps non-ASCII characters (like emojis or accented letters) as-is instead of converting them to \u sequences.
  • skipkeys=True – skips keys that are not basic types (e.g., tuples) instead of raising a TypeError.

Example with all options:

print(json.dumps(data, indent=4, sort_keys=True, ensure_ascii=False))

Common Problems and Misconceptions

A frequent mistake is confusing json.dumps() with json.dump(). The former returns a string; the latter writes directly to a file object. If you call json.dump(data, indent=2) without a file, you get an error. Another issue is forgetting to import json – this raises a NameError. Also, indent must be an integer or a string; passing None (the default) produces compact output without newlines.

Misconception: some think pretty-printing changes the JSON data itself. It does not – it only changes the string representation. When you parse the pretty string back with json.loads(), you get the same Python object.

Alternatives to json.dumps()

If you need even more control or want to pretty-print JSON from the command line, consider:

  • pprint module – Python’s built-in pprint can format Python data structures, but its output is not valid JSON (it uses single quotes and Python literals).
  • jq – a command-line tool for JSON processing; jq . file.json pretty-prints with two-space indentation.
  • Online formatters – many web tools exist, but they require copying data and may not be suitable for sensitive information.
  • json.tool – a built-in Python module: python -m json.tool input.json prints pretty-printed JSON to stdout.

Performance Considerations

Pretty-printing increases output size due to added whitespace and newlines. For very large JSON files (hundreds of MB), this can slow down serialization and consume extra memory. If performance is critical, use the default compact output for storage and only pretty-print for debugging or display. Also, sort_keys=True adds overhead, so avoid it in performance-sensitive loops.

Frequently Asked Questions

How do I pretty-print JSON to a file in Python?

Use json.dump(data, file_object, indent=2). For example: with open('output.json', 'w') as f: json.dump(data, f, indent=2). This writes the pretty-printed JSON directly to the file without creating an intermediate string.

What is the difference between indent=2 and indent=4?

It’s purely visual. indent=2 uses two spaces per nesting level; indent=4 uses four. Some style guides prefer 2 for compactness, others 4 for clarity. There is no functional difference.

Why does my JSON print with \u escapes instead of Unicode characters?

By default, json.dumps() sets ensure_ascii=True, which escapes non-ASCII characters. Pass ensure_ascii=False to keep them as-is. This is common when dealing with languages like Chinese or Arabic.

Can I pretty-print JSON from a string, not a Python object?

Yes. First parse the string with json.loads() to get a Python object, then pretty-print with json.dumps(). For example: data = json.loads(json_str); print(json.dumps(data, indent=2)).

How do I pretty-print JSON in the Python console or REPL?

In the interactive console, you can use the same json.dumps() method. Alternatively, the pprint module works for Python objects but not for JSON strings directly. For a quick one-liner, use python -m json.tool on a file.

Is there a way to pretty-print JSON without writing any code?

Yes, use the command line: echo '{"a":1}' | python -m json.tool or use jq if installed. These tools format JSON without needing to write a script.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →