50 lines
1.3 KiB
Python
50 lines
1.3 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
JSON Key Counter Utility
|
|
Recursively counts all keys in a JSON file, including nested keys.
|
|
"""
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def count_keys(obj, prefix=""):
|
|
"""Recursively count all keys in a JSON structure."""
|
|
count = 0
|
|
if isinstance(obj, dict):
|
|
for key, value in obj.items():
|
|
full_key = f"{prefix}.{key}" if prefix else key
|
|
count += 1 # Count this key
|
|
count += count_keys(value, full_key) # Recurse into value
|
|
elif isinstance(obj, list):
|
|
for i, item in enumerate(obj):
|
|
count += count_keys(item, f"{prefix}[{i}]")
|
|
return count
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) < 2:
|
|
print("Usage: json_key_counter.py <json_file>")
|
|
sys.exit(1)
|
|
|
|
filepath = Path(sys.argv[1])
|
|
|
|
try:
|
|
content = filepath.read_text().strip()
|
|
if not content:
|
|
print(f"Error: Empty file {filepath}")
|
|
sys.exit(1)
|
|
|
|
data = json.loads(content)
|
|
key_count = count_keys(data)
|
|
print(f"{filepath}: {key_count} keys")
|
|
except json.JSONDecodeError as e:
|
|
print(f"Invalid JSON in {filepath}: {e}")
|
|
sys.exit(1)
|
|
except FileNotFoundError:
|
|
print(f"File not found: {filepath}")
|
|
sys.exit(1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |