47 lines
1.3 KiB
Python
47 lines
1.3 KiB
Python
#!/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() |