spark: add JSON path finder utility
This commit is contained in:
1 parent
d129177701
commit
c606aa99f0
1 file changed
+47
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env python3
|
||||
"""JSON path finder - extracts values at given JSON paths from files."""
|
||||
import sys
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
def get_nested_value(data, path):
|
||||
"""Get value at dotted path like 'users.0.name'."""
|
||||
keys = path.split('.')
|
||||
result = data
|
||||
for key in keys:
|
||||
if key.isdigit():
|
||||
key = int(key)
|
||||
if isinstance(result, dict):
|
||||
result = result.get(key)
|
||||
elif isinstance(result, list) and isinstance(key, int):
|
||||
result = result[key] if key < len(result) else None
|
||||
else:
|
||||
return None
|
||||
if result is None:
|
||||
return None
|
||||
return result
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 3:
|
||||
print("Usage: json_path_finder.py <json_file> <path>", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
json_file = Path(sys.argv[1])
|
||||
path = sys.argv[2]
|
||||
|
||||
try:
|
||||
data = json.loads(json_file.read_text())
|
||||
value = get_nested_value(data, path)
|
||||
if value is None:
|
||||
print(f"Path '{path}' not found")
|
||||
sys.exit(1)
|
||||
print(json.dumps(value, indent=2))
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"Invalid JSON: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
except FileNotFoundError:
|
||||
print(f"File not found: {json_file}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user