python-json-config

1.2.3 · maintenance · verified Mon Apr 13

This library (version 1.2.3) provides a convenient way to load JSON configuration files, allowing access to values using dot notation (e.g., `config.server.port`). It also includes features for validating config field types and values, and transforming fields. The library's last update was in November 2019, indicating a maintenance-only or inactive release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `ConfigBuilder`, parse a JSON configuration file, and access nested values using convenient dot notation. It also includes an example of validating field types and how environment variables can be used for configuration values.

import os
import tempfile

# Create a dummy config.json for the example
config_content = '''
{
    "server": {
        "host": "localhost",
        "port": 8080
    },
    "database": {
        "name": "mydb",
        "user": "admin"
    },
    "jwt_secret": "${JWT_SECRET:-default_secret_key}"
}
'''

with tempfile.TemporaryDirectory() as tmpdir:
    config_path = os.path.join(tmpdir, 'config.json')
    with open(config_path, 'w') as f:
        f.write(config_content)

    # Set an environment variable to demonstrate its use
    os.environ['JWT_SECRET'] = 'my_super_secret_jwt_key'

    from python_json_config import ConfigBuilder

    # Create config parser
    builder = ConfigBuilder()

    # Parse config from the temporary file
    config = builder.parse_config(config_path)

    # Access elements using dot notation
    host = config.server.host
    port = config.server.port
    db_name = config.database.name
    jwt_secret = config.jwt_secret # This will pick up from os.environ

    print(f"Server Host: {host}")
    print(f"Server Port: {port}")
    print(f"Database Name: {db_name}")
    print(f"JWT Secret: {jwt_secret}")

    # Validate field types
    builder.validate_field_type('server.port', int)
    builder.validate_field_type('database.user', str)
    print("Configuration fields validated successfully.")

    # Clean up environment variable
    del os.environ['JWT_SECRET']

view raw JSON →