Project Introduction
Configuration files are one of the most important use cases for JSON. This tutorial will demonstrate how to use JSON to build a flexible configuration management system.
💡 Advantages: Clear structure, easy to modify, supports nesting, language-independent
Configuration File Example
A typical application configuration file:
{
"app": {
"name": "MyApp",
"version": "1.0.0",
"debug": false,
"env": "production"
},
"database": {
"host": "localhost",
"port": 5432,
"name": "mydb",
"username": "admin",
"password": "secret"
},
"server": {
"host": "0.0.0.0",
"port": 8000,
"ssl": true
},
"features": {
"enableCache": true,
"enableLogs": true,
"maxConnections": 100
}
}
Config Manager Implementation
Python Implementation Example:
import json
from pathlib import Path
class ConfigManager:
def __init__(self, config_file='config.json'):
self.config_file = Path(config_file)
self.config = {}
self.load()
def load(self):
"""Load config from file"""
if self.config_file.exists():
with open(self.config_file, 'r') as f:
self.config = json.load(f)
else:
self.create_default()
def get(self, key, default=None):
"""Get config value, supports nested keys like 'database.host'"""
keys = key.split('.')
value = self.config
for k in keys:
if isinstance(value, dict):
value = value.get(k)
else:
return default
return value if value is not None else default
def set(self, key, value):
"""Set config value"""
keys = key.split('.')
config = self.config
for k in keys[:-1]:
if k not in config:
config[k] = {}
config = config[k]
config[keys[-1]] = value
self.save()
def save(self):
"""Save config to file"""
with open(self.config_file, 'w') as f:
json.dump(self.config, f, indent=2)
# Usage Example
config = ConfigManager()
print(config.get('database.host')) # localhost
config.set('server.port', 9000)
config.save()
Environment Configuration Separation
Use different config files for different environments:
Dev Env
config.dev.json
Test Env
config.test.json
Prod Env
config.prod.json
🎉 Congratulations!
You have mastered all core knowledge of JSON from basics to practice.