spark: add JSON validator CLI tool with tests
This commit is contained in:
1 parent
48a40ce128
commit
3168679020
3 files changed
+47
-58
No files matched your search
@@ -1,81 +1,51 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
JSON Validator - Validates JSON files with detailed error reporting.
|
||||
Usage: python3 json_validator.py <file.json> [file2.json ...]
|
||||
"""
|
||||
"""Simple JSON validator CLI - validates JSON files and reports errors."""
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def validate_json_file(filepath: str) -> dict[str, Any]:
|
||||
"""Validate a JSON file and return analysis results."""
|
||||
result = {
|
||||
"file": filepath,
|
||||
"valid": False,
|
||||
"error": None,
|
||||
"type": None,
|
||||
"size": None,
|
||||
"line_count": None,
|
||||
"structure": None
|
||||
}
|
||||
|
||||
path = Path(filepath)
|
||||
if not path.exists():
|
||||
result["error"] = f"File not found: {filepath}"
|
||||
return result
|
||||
|
||||
result["size"] = path.stat().st_size
|
||||
def validate_json_file(filepath: str) -> tuple[bool, str]:
|
||||
"""Validate a JSON file.
|
||||
|
||||
Returns:
|
||||
(True, "") if valid
|
||||
(False, error_message) if invalid
|
||||
"""
|
||||
try:
|
||||
with open(path, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
result["line_count"] = content.count('\n') + 1
|
||||
|
||||
data = json.loads(content)
|
||||
result["valid"] = True
|
||||
result["type"] = type(data).__name__
|
||||
|
||||
if isinstance(data, dict):
|
||||
result["structure"] = f"Object with {len(data)} keys"
|
||||
elif isinstance(data, list):
|
||||
result["structure"] = f"Array with {len(data)} elements"
|
||||
else:
|
||||
result["structure"] = f"Scalar value: {type(data).__name__}"
|
||||
|
||||
with open(filepath, 'r') as f:
|
||||
json.load(f)
|
||||
return True, ""
|
||||
except FileNotFoundError:
|
||||
return False, f"Error: File not found: {filepath}"
|
||||
except json.JSONDecodeError as e:
|
||||
result["error"] = f"Line {e.lineno}, Column {e.colno}: {e.msg}"
|
||||
except UnicodeDecodeError as e:
|
||||
result["error"] = f"Encoding error: {e.reason}"
|
||||
return False, f"Error: Invalid JSON at line {e.lineno}, column {e.colno}: {e.msg}"
|
||||
except Exception as e:
|
||||
result["error"] = f"Unexpected error: {e}"
|
||||
|
||||
return result
|
||||
return False, f"Error reading file: {e}"
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print("Usage: python3 json_validator.py <file.json> [file2.json ...]")
|
||||
print("\nValidates JSON files with detailed error reporting.")
|
||||
print("Usage: json_validator.py <file1.json> [file2.json] ...", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
files = sys.argv[1:]
|
||||
results = [validate_json_file(f) for f in files]
|
||||
all_valid = True
|
||||
results = []
|
||||
|
||||
for filepath in files:
|
||||
valid, error = validate_json_file(filepath)
|
||||
if valid:
|
||||
results.append(f"✓ VALID: {filepath}")
|
||||
else:
|
||||
results.append(f"✗ INVALID: {filepath} - {error}")
|
||||
all_valid = False
|
||||
|
||||
for r in results:
|
||||
status = "✓ VALID" if r["valid"] else "✗ INVALID"
|
||||
print(f"\n{status}: {r['file']}")
|
||||
|
||||
if r["valid"]:
|
||||
print(f" Type: {r['type']}")
|
||||
print(f" Structure: {r['structure']}")
|
||||
print(f" Size: {r['size']} bytes, {r['line_count']} lines")
|
||||
else:
|
||||
print(f" Error: {r['error']}")
|
||||
print(r)
|
||||
|
||||
# Exit with error code if any file is invalid
|
||||
sys.exit(0 if all(r["valid"] for r in results) else 1)
|
||||
sys.exit(0 if all_valid else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "test",
|
||||
"value": 42,
|
||||
"items": ["a", "b", "c"]
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify the hermes_diagnostics output has status 'ok'."""
|
||||
import json
|
||||
import sys
|
||||
|
||||
with open("/root/troupe-standup/wizard-work/spark/output.json") as f:
|
||||
data = json.load(f)
|
||||
|
||||
if data.get("status") == "ok":
|
||||
print("VERIFIED: status is ok")
|
||||
sys.exit(0)
|
||||
else:
|
||||
print("FAILED: status is not ok")
|
||||
sys.exit(1)
|
||||
Reference in new issue
Block a user