From 089faff3a3571e3ecb5be2c61d403a7f778f2b60 Mon Sep 17 00:00:00 2001 From: Mark Eaton Date: Wed, 17 Sep 2025 19:08:44 -0400 Subject: [PATCH] feat: add script to pretty-print JSON Lines (.jsonl) files with indentation option Co-authored-by: aider (o3) --- scripts/jsonl_pretty_print.py | 64 +++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 scripts/jsonl_pretty_print.py diff --git a/scripts/jsonl_pretty_print.py b/scripts/jsonl_pretty_print.py new file mode 100644 index 0000000..d8332ed --- /dev/null +++ b/scripts/jsonl_pretty_print.py @@ -0,0 +1,64 @@ +#!/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 + # Dump the pretty JSON followed by a newline separator + print(json.dumps(obj, indent=indent, ensure_ascii=False, sort_keys=True)) + print() # blank line between records for readability + + +def main() -> None: + args = parse_args() + pretty_print_jsonl(args.jsonl_path, args.indent) + + +if __name__ == "__main__": + main()