#!/usr/bin/env python3
"""
Configuration File Parser and Validator.
This script parses a JSON configuration file and validates it against a predefined schema.
The schema expects the following structure:
{
"host": "string" (non-empty),
"port": int (between 1 and 65535),
"debug": bool,
"database": {
"url": "string"
}
}
Usage:
python config_validator.py /path/to/config.json
If valid, it prints "Configuration is valid." followed by the pretty-printed config.
If invalid, it prints errors and exits with code 1.
"""
import json
import argparse
import sys
def validate_config(config):
"""
Validates the parsed config dictionary against the schema.
Returns (is_valid: bool, errors: list[str])
"""
errors = []
if not isinstance(config, dict):
errors.append("Root config must be a dictionary")
return False, errors
# Required top-level keys
required_top = ['host', 'port', 'debug', 'database']
for key in required_top:
if key not in config:
errors.append(f"Missing required key: '{key}'")
continue # Still check others
value = config[key]
if key == 'host':
if not isinstance(value, str) or not value.strip():
errors.append("host: must be a non-empty string")
elif key == 'port':
if not isinstance(value, int) or not (1 <= value <= 65535):
errors.append("port: must be an integer between 1 and 65535")
elif key == 'debug':
if not isinstance(value, bool):
errors.append("debug: must be a boolean")
elif key == 'database':
if not isinstance(value, dict):
errors.append("database: must be a dictionary")
else:
db_url = value.get('url')
if db_url is None or not isinstance(db_url, str):
errors.append("database.url: must be a string")
return len(errors) == 0, errors
def main():
parser = argparse.ArgumentParser(
description="Parse and validate a JSON configuration file."
)
parser.add_argument(
'config_file',
help="Path to the JSON configuration file"
)
args = parser.parse_args()
# Parse JSON
try:
with open(args.config_file, 'r') as f:
config = json.load(f)
except FileNotFoundError:
print(f"Error: Config file not found: {args.config_file}", file=sys.stderr)
sys.exit(1)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON in {args.config_file}: {e}", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Error reading file: {e}", file=sys.stderr)
sys.exit(1)
# Validate
is_valid, errors = validate_config(config)
if is_valid:
print("✓ Configuration is valid.")
print(json.dumps(config, indent=2))
else:
print("✗ Configuration validation failed:", file=sys.stderr)
for error in errors:
print(f" - {error}", file=sys.stderr)
sys.exit(1)
if __name__ == '__main__':
main()
Sample Configuration File (config.json)
Save this as config.json to test:
{
"host": "localhost",
"port": 8080,
"debug": true,
"database": {
"url": "postgresql://user:pass@localhost/mydb"
}
}
Testing
# Valid config
python config_validator.py config.json
# Invalid examples (try modifying config.json)
# - Remove "host" → Missing required key
# - Set "port": "abc" → Type/range error
# - Set "debug": 1 → Type error
Features
- Standard Library Only: No external dependencies.
- Robust Error Handling: File I/O, JSON parsing, and validation errors.
- Extensible: Easily add more validation rules in
validate_config().
- CLI-Friendly: Uses
argparse for input; pretty-prints valid configs.
This script can be extended for YAML (add pyyaml), TOML (tomllib in Python 3.11+), or custom schemas. Let me know if you need modifications!