124 lines
4.5 KiB
Python
Executable File
124 lines
4.5 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""jsongrep — grep inside JSON values by key path.
|
|
Usage: jsongrep [--key PATTERN] [--value REGEX] [--ignore-case] [FILE]
|
|
Reads stdin when no FILE is given. Walks a JSON document and prints every
|
|
path=value whose key path matches PATTERN (dot-separated, * = any segment) or
|
|
whose value matches REGEX — grep for structured data instead of raw text.
|
|
"""
|
|
import argparse, json, re, sys
|
|
|
|
|
|
def walk(node, path, out):
|
|
if isinstance(node, dict):
|
|
for k, v in node.items():
|
|
walk(v, path + [str(k)], out)
|
|
elif isinstance(node, list):
|
|
for i, v in enumerate(node):
|
|
walk(v, path + [str(i)], out)
|
|
else:
|
|
out.append((".".join(path), node))
|
|
|
|
|
|
def path_matches(path, pattern, ignore_case):
|
|
pat_segs = pattern.split(".")
|
|
path_segs = path.split(".")
|
|
if len(pat_segs) != len(path_segs):
|
|
# allow a trailing * to swallow the rest, and a leading pattern to
|
|
# match any suffix when it has fewer segments
|
|
if len(pat_segs) < len(path_segs) and pat_segs and pat_segs[-1] == "*":
|
|
pat_segs = pat_segs[:-1] + ["*"] * (len(path_segs) - len(pat_segs) + 1)
|
|
else:
|
|
return False
|
|
for p, s in zip(pat_segs, path_segs):
|
|
if p == "*":
|
|
continue
|
|
if ignore_case:
|
|
if p.lower() != s.lower():
|
|
return False
|
|
elif p != s:
|
|
return False
|
|
return True
|
|
|
|
|
|
def main(argv=None):
|
|
ap = argparse.ArgumentParser(prog="jsongrep",
|
|
description="Grep inside JSON values by key path.")
|
|
ap.add_argument("file", nargs="?", help="JSON file (default: stdin)")
|
|
ap.add_argument("--key", help="key path pattern, dot-separated, * = any segment (e.g. users.*.email)")
|
|
ap.add_argument("--value", help="regex matched against stringified values")
|
|
ap.add_argument("--ignore-case", action="store_true", help="case-insensitive matching")
|
|
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()
|
|
if not a.key and not a.value:
|
|
print("jsongrep: give --key and/or --value", file=sys.stderr)
|
|
return 2
|
|
flags = re.IGNORECASE if a.ignore_case else 0
|
|
try:
|
|
vrx = re.compile(a.value, flags) if a.value else None
|
|
except re.error as e:
|
|
print(f"jsongrep: bad --value regex: {e}", file=sys.stderr)
|
|
return 2
|
|
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"jsongrep: {e}", file=sys.stderr)
|
|
return 1
|
|
except json.JSONDecodeError as e:
|
|
print(f"jsongrep: invalid JSON: {e}", file=sys.stderr)
|
|
return 1
|
|
leaves = []
|
|
walk(data, [], leaves)
|
|
hits = 0
|
|
for path, val in leaves:
|
|
ok = True
|
|
if a.key and not path_matches(path, a.key, a.ignore_case):
|
|
ok = False
|
|
if ok and vrx and not vrx.search(str(val)):
|
|
ok = False
|
|
if ok:
|
|
print(f"{path} = {val!r}")
|
|
hits += 1
|
|
print(f"jsongrep: {hits} match(es) in {len(leaves)} leaf value(s)", file=sys.stderr)
|
|
return 0 if hits else 1
|
|
|
|
|
|
def selftest():
|
|
import io
|
|
from contextlib import redirect_stdout
|
|
data = {"users": [{"name": "amy", "email": "amy@x.com"}, {"name": "bob", "email": "bob@y.org"}],
|
|
"meta": {"version": 3}}
|
|
leaves = []
|
|
walk(data, [], leaves)
|
|
assert ("users.0.email", "amy@x.com") in leaves, leaves
|
|
assert path_matches("users.0.email", "users.*.email", False)
|
|
assert not path_matches("users.0.name", "users.*.email", False)
|
|
assert path_matches("meta.version", "meta.*", False)
|
|
import tempfile, os, json
|
|
with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as fh:
|
|
json.dump(data, fh)
|
|
path = fh.name
|
|
try:
|
|
buf = io.StringIO()
|
|
with redirect_stdout(buf):
|
|
rc = main(["--key", "users.*.email", path])
|
|
assert rc == 0 and "amy@x.com" in buf.getvalue(), buf.getvalue()
|
|
buf = io.StringIO()
|
|
with redirect_stdout(buf):
|
|
rc = main(["--value", "y\\.org", path])
|
|
assert rc == 0 and "bob@y.org" in buf.getvalue(), buf.getvalue()
|
|
assert main(["--key", "nope.*", path]) == 1
|
|
finally:
|
|
os.unlink(path)
|
|
print("jsongrep selftest: PASS")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|