spark: add json_key_counter utility for recursive key counting

This commit is contained in:
spark committed 2026-10-26 08:46:00 +00:00
1 parent 667bf395d2
commit 8474ce3163
1 file changed
+50
+50
View File
@@ -0,0 +1,50 @@
#!/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()