71 lines
1.9 KiB
Python
71 lines
1.9 KiB
Python
#!/usr/bin/env python3
|
|
"""JSON validation and formatting utility."""
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def validate_json(file_path: str) -> dict:
|
|
"""Validate a JSON file and return result dict."""
|
|
path = Path(file_path)
|
|
result = {"file": file_path, "valid": False, "error": None, "size": 0}
|
|
|
|
if not path.exists():
|
|
result["error"] = "File not found"
|
|
return result
|
|
|
|
result["size"] = path.stat().st_size
|
|
|
|
try:
|
|
with open(path, 'r') as f:
|
|
data = json.load(f)
|
|
result["valid"] = True
|
|
result["parsed"] = type(data).__name__
|
|
except json.JSONDecodeError as e:
|
|
result["error"] = str(e)
|
|
except Exception as e:
|
|
result["error"] = f"Read error: {e}"
|
|
|
|
return result
|
|
|
|
|
|
def format_json(file_path: str, output_path: str = None, indent: int = 2) -> str:
|
|
"""Format a JSON file with proper indentation."""
|
|
result = validate_json(file_path)
|
|
|
|
if not result["valid"]:
|
|
return json.dumps({"error": result["error"]}, indent=2)
|
|
|
|
with open(file_path, 'r') as f:
|
|
data = json.load(f)
|
|
|
|
formatted = json.dumps(data, indent=indent, sort_keys=False)
|
|
|
|
if output_path:
|
|
with open(output_path, 'w') as f:
|
|
f.write(formatted)
|
|
return formatted
|
|
return formatted
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) < 2:
|
|
print("Usage: python json-toolkit.py <file.json> [output.json]")
|
|
sys.exit(1)
|
|
|
|
input_file = sys.argv[1]
|
|
|
|
print(f"Validating: {input_file}")
|
|
result = validate_json(input_file)
|
|
|
|
if result["valid"]:
|
|
print(f" Status: VALID")
|
|
print(f" Type: {result['parsed']}")
|
|
print(f" Size: {result['size']} bytes")
|
|
print("\nFormatted content:")
|
|
print(format_json(input_file))
|
|
else:
|
|
print(f" Status: INVALID")
|
|
print(f" Error: {result['error']}")
|
|
|
|
sys.exit(0 if result["valid"] else 1) |