Files

109 lines
4.1 KiB
Python
Executable File

#!/usr/bin/env python3
"""jsonpeek — summarize JSON structure: keys, types, depth, size, sample values.
Usage: jsonpeek [--max-depth N] [--max-keys N] [FILE]
Reads stdin when no FILE is given. Answers "what shape is this JSON?" for files
too big to eyeball: a tree of keys with types, array lengths, depth, and samples.
"""
import argparse, json, sys
def type_name(v):
if v is None:
return "null"
if isinstance(v, bool):
return "bool"
if isinstance(v, int):
return "int"
if isinstance(v, float):
return "float"
if isinstance(v, str):
return "str"
if isinstance(v, list):
return "list"
if isinstance(v, dict):
return "dict"
return type(v).__name__
def depth_of(v):
if isinstance(v, dict):
return 1 + max((depth_of(x) for x in v.values()), default=0)
if isinstance(v, list):
return 1 + max((depth_of(x) for x in v), default=0)
return 0
def summarize(v, max_depth, max_keys, indent=0):
lines = []
pad = " " * indent
if isinstance(v, dict):
items = list(v.items())
lines.append(f"{pad}dict[{len(items)} keys]")
for k, val in items[:max_keys]:
t = type_name(val)
if isinstance(val, dict):
lines.append(f"{pad} {k}: dict[{len(val)} keys]")
if indent + 1 < max_depth:
lines.extend(summarize(val, max_depth, max_keys, indent + 2))
elif isinstance(val, list):
et = sorted({type_name(x) for x in val})
lines.append(f"{pad} {k}: list[{len(val)}] of {','.join(et) or '?'}"
+ (f" e.g. {val[0]!r}" if val and not isinstance(val[0], (dict, list)) else ""))
if val and isinstance(val[0], (dict, list)) and indent + 1 < max_depth:
lines.extend(summarize(val[0], max_depth, max_keys, indent + 2))
else:
lines.append(f"{pad} {k}: {t} = {val!r}"[:120])
if len(items) > max_keys:
lines.append(f"{pad} ... and {len(items) - max_keys} more keys")
elif isinstance(v, list):
et = sorted({type_name(x) for x in v})
lines.append(f"{pad}list[{len(v)}] of {','.join(et) or '?'}")
if v and isinstance(v[0], (dict, list)) and indent < max_depth:
lines.extend(summarize(v[0], max_depth, max_keys, indent + 1))
else:
lines.append(f"{pad}{type_name(v)} = {v!r}"[:120])
return lines
def main(argv=None):
ap = argparse.ArgumentParser(prog="jsonpeek",
description="Summarize JSON structure: keys, types, depth, size, sample values.")
ap.add_argument("file", nargs="?", help="JSON file (default: stdin)")
ap.add_argument("--max-depth", type=int, default=4, help="how deep to expand (default 4)")
ap.add_argument("--max-keys", type=int, default=25, help="keys shown per object (default 25)")
ap.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
argv_list = list(argv) if argv is not None else sys.argv[1:]
if "--selftest" in argv_list:
return selftest()
a = ap.parse_args(argv)
if a.selftest:
return selftest()
try:
raw = open(a.file, encoding="utf-8").read() if a.file else sys.stdin.read()
data = json.loads(raw)
except OSError as e:
print(f"jsonpeek: {e}", file=sys.stderr)
return 1
except json.JSONDecodeError as e:
print(f"jsonpeek: invalid JSON: {e}", file=sys.stderr)
return 1
print(f"top: {type_name(data)} depth: {depth_of(data)} size: {len(raw)} bytes")
for line in summarize(data, a.max_depth, a.max_keys):
print(line)
return 0
def selftest():
sample = {"name": "amy", "age": 31, "tags": ["a", "b"], "addr": {"city": "Reno", "zip": 89501}}
assert depth_of(sample) == 2
lines = summarize(sample, 4, 25)
joined = "\n".join(lines)
assert "name: str = 'amy'" in joined and "tags: list[2] of str" in joined, joined
assert "city: str = 'Reno'" in joined, joined
print("jsonpeek selftest: PASS")
return 0
if __name__ == "__main__":
sys.exit(main())