python
#!/usr/bin/env python3
"""
JSON Validator and Cleaner Tool
This tool validates JSON data and cleans common malformations such as:
- C-style and line comments (//, /* */)
- Unquoted object keys
- Single-quoted strings (roughly; assumes no escaped single quotes inside strings)
- Trailing commas in objects and arrays
Usage:
python json_tool.py [input.json] [-o output.json] [--pretty] [--strict] [--clean-only] [--verbose]
Examples:
cat data.json | python json_tool.py -o cleaned.json --pretty
python json_tool.py bad.json --strict
"""
import sys
import json
import argparse
import re
def remove_comments(json_str: str) -> str:
"""Remove // and /* */ comments."""
# Line comments
json_str = re.sub(r'//.*?(?=\n|$)', '', json_str, flags=re.MULTILINE)
# Block comments (non-greedy, handles simple non-nested cases)
json_str = re.sub(r'/\*[\s\S]*?\*/', '', json_str)
return json_str
def fix_unquoted_keys(json_str: str) -> str:
"""Quote unquoted object keys (excluding true/false/null)."""
# Match identifiers not true/false/null followed by :
pattern = r'\b(?!true\b|false\b|null\b)([a-zA-Z_$][a-zA-Z0-9_$]*)(\s*):'
replacement = r'"\1"\2:'
return re.sub(pattern, replacement, json_str)
def fix_single_quotes(json_str: str) -> str:
"""Roughly replace single-quoted strings with double quotes.
WARNING: Does not handle escaped single quotes inside strings perfectly."""
# Simple replacement; assumes no \' inside single-quoted strings
return re.sub(r"'([^']*)'", r'"\1"', json_str)
def remove_trailing_commas(json_str: str) -> str:
"""Remove trailing commas before } or ]."""
return re.sub(r',\s*([}\]])', r'\1', json_str)
def clean_json(json_str: str) -> str:
"""Apply all cleaning steps in order."""
json_str = remove_comments(json_str)
json_str = fix_unquoted_keys(json_str)
json_str = fix_single_quotes(json_str)
json_str = remove_trailing_commas(json_str)
return json_str.strip()
def validate_json(json_str: str) -> tuple[bool, dict | list | None, str]:
"""Validate JSON string, return (is_valid, parsed_obj, error_msg)."""
try:
parsed = json.loads(json_str)
return True, parsed, ""
except json.JSONDecodeError as e:
return False, None, str(e)
def main():
parser = argparse.ArgumentParser(
description="Validate and clean JSON data.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__
)
parser.add_argument(
'input', nargs='?', default=None,
help='Input file (default: stdin)'
)
parser.add_argument(
'-o', '--output', default=None,
help='Output file (default: stdout)'
)
parser.add_argument(
'--pretty', '-p', action='store_true',
help='Pretty-print output with indentation'
)
parser.add_argument(
'--strict', action='store_true',
help='Strict validation only (no cleaning)'
)
parser.add_argument(
'--clean-only', action='store_true',
help='Clean only (no validation or pretty-print)'
)
parser.add_argument(
'-v', '--verbose', action='store_true',
help='Verbose output: show original vs cleaned'
)
args = parser.parse_args()
# Read input
if args.input:
try:
with open(args.input, 'r', encoding='utf-8') as f:
data = f.read()
except IOError as e:
print(f"Error reading {args.input}: {e}", file=sys.stderr)
sys.exit(1)
else:
data = sys.stdin.read()
if not data.strip():
print("Error: Empty input", file=sys.stderr)
sys.exit(1)
original = data
output_str = ""
status_msg = ""
if args.strict:
# Strict validation only
is_valid, _, err = validate_json(original)
if is_valid:
parsed = json.loads(original)
output_str = json.dumps(parsed, indent=2 if args.pretty else None)
status_msg = "Valid JSON"
else:
status_msg = f"Invalid JSON: {err}"
output_str = ""
elif args.clean_only:
# Clean only
cleaned = clean_json(original)
output_str = cleaned
status_msg = "Cleaned JSON (not validated)"
else:
# Clean + validate
cleaned = clean_json(original)
is_valid, parsed, err = validate_json(cleaned)
if is_valid:
output_str = json.dumps(parsed, indent=2 if args.pretty else None)
status_msg = "Cleaned and validated successfully"
else:
status_msg = f"Cleaning failed to produce valid JSON: {err}"
output_str = cleaned # Output cleaned anyway
# Verbose: show diff
if args.verbose:
print("Original:\n---\n" + original + "\n---")
if not args.clean_only and not args.strict:
print("Cleaned:\n---\n" + clean_json(original) + "\n---")
# Status
print(status_msg, file=sys.stderr)
# Output
if output_str:
out_file = sys.stdout if args.output is None else open(args.output, 'w', encoding='utf-8')
print(output_str, file=out_file, end='')
if args.output:
out_file.close()
# Exit code
sys.exit(0 if "success" in status_msg or args.clean_only else 1)
if __name__ == '__main__':
main()