feat: add script to pretty-print JSON Lines (.jsonl) files with indentation option
Co-authored-by: aider (o3) <aider@aider.chat>
This commit is contained in:
@@ -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()
|
||||
Reference in New Issue
Block a user