JSON Configuration
JSON is popular for application config files. Merge defaults with user overrides using dict unpacking or deep merge.
JSON is popular for application config files. Merge defaults with user overrides using dict unpacking or deep merge.
import json
from pathlib import Path
def load_config(path: str, defaults: dict) -> dict:
cfg_path = Path(path)
user_cfg = json.loads(cfg_path.read_text()) if cfg_path.exists() else {}
return {**defaults, **user_cfg} # shallow merge
defaults = {"debug": False, "port": 8000, "db": {"host": "localhost", "port": 5432}}
config = load_config("config.json", defaults)
print(config["port"])
For deeply nested configs, use recursive merge or consider TOML/YAML which support comments.