第十一章

实战项目:配置管理系统

使用 JSON 管理应用配置

项目介绍

配置文件是 JSON 的重要应用场景之一。本教程将演示如何使用 JSON 构建一个灵活的配置管理系统。

💡 优势:结构清晰、易于修改、支持嵌套、跨语言通用

配置文件示例

一个典型的应用配置文件:

{
  "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
  }
}

配置管理类实现

Python 实现示例:

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):
        """从文件加载配置"""
        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):
        """获取配置值,支持嵌套键如 '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):
        """设置配置值"""
        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):
        """保存配置到文件"""
        with open(self.config_file, 'w') as f:
            json.dump(self.config, f, indent=2)

# 使用示例
config = ConfigManager()
print(config.get('database.host'))  # localhost
config.set('server.port', 9000)
config.save()

环境配置分离

不同环境使用不同的配置文件:

开发环境

config.dev.json

测试环境

config.test.json

生产环境

config.prod.json

🎉 恭喜完成教程!

你已经掌握了 JSON 从基础到实战的所有核心知识

✅ 基础概念
对象、数组、嵌套
✅ 实战应用
Python、JS、Java
✅ 进阶技能
Schema、性能
✅ 项目经验
API、配置管理