SyntaxStudy
Sign Up
Python Configuration with JSON
Python Beginner 3 min read

Configuration with JSON

JSON Configuration

JSON is popular for application config files. Merge defaults with user overrides using dict unpacking or deep merge.

Example
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"])
Pro Tip

For deeply nested configs, use recursive merge or consider TOML/YAML which support comments.