← all snippets

json-pretty-print

Reads a JSON file, validates it, and prints it back indented and readable. Use it to sanity-check a config file or eyeball an API response saved to disk.

Python 3 #02

Source

json-pretty-print.py
#!/usr/bin/env python3
"""Validate a JSON file and pretty-print it."""
import json
import sys

if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit("usage: json-pretty-print.py <path>")
    try:
        with open(sys.argv[1], "r", encoding="utf-8") as f:
            data = json.load(f)
    except OSError as e:
        sys.exit(f"error: {e}")
    except json.JSONDecodeError as e:
        sys.exit(f"invalid JSON: {e}")
    print(json.dumps(data, indent=2, ensure_ascii=False))

Input

pathstring — positional argument, path to a .json file, e.g. config.json

Output

Prints the JSON re-formatted with 2-space indentation to stdout, exit 0. If the file is missing/unreadable or not valid JSON, exits non-zero with a one-line error on stderr instead of a stack trace.

Usage

$ python3 json-pretty-print.py config.json
{
  "name": "svc",
  "port": 8080
}

Config

No configuration required.

Security notes

  • Uses json.load, which only parses data (no code execution), unlike eval-based approaches.
  • Malformed JSON is caught and reported cleanly instead of leaking a raw traceback.