#!/usr/bin/env python3 """ Pretty-print a JSON Lines (.jsonl) file. Usage ----- python scripts/jsonl_pretty_print.py path/to/file.jsonl [--indent 2] The script reads each line, parses it as JSON, and writes a human-readable representation to stdout. Redirect or pipe as needed. Example ------- python scripts/jsonl_pretty_print.py data.jsonl --indent 4 > pretty.json """ from __future__ import annotations import argparse import json import sys from pathlib import Path def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Pretty-print a .jsonl file.") parser.add_argument( "jsonl_path", type=Path, help="Path to the input .jsonl file", ) parser.add_argument( "--indent", type=int, default=2, help="Number of spaces to indent (default: 2)", ) return parser.parse_args() def pretty_print_jsonl(path: Path, indent: int) -> None: if not path.exists(): sys.exit(f"Error: {path} does not exist") with path.open("r", encoding="utf-8") as fp: for idx, line in enumerate(fp, start=1): line = line.strip() if not line: continue # skip empty lines try: obj = json.loads(line) except json.JSONDecodeError as exc: sys.exit(f"JSON decode error on line {idx}: {exc}") # fail fast # Build pretty JSON string, convert literal "\n" sequences to real newlines, # and emit a blank line between records for readability. pretty = json.dumps(obj, indent=indent, ensure_ascii=False, sort_keys=True) pretty = pretty.replace("\\n", "\n") sys.stdout.write(pretty) sys.stdout.write("\n\n") def main() -> None: args = parse_args() pretty_print_jsonl(args.jsonl_path, args.indent) if __name__ == "__main__": main()