INI 转 JSON 工具

INI 和 JSON 格式双向转换工具,支持配置文件格式转换和语法验证

格式信息

INI 格式

  • 使用 [section] 定义配置节
  • 支持 key=value 键值对
  • 支持 # 和 ; 注释
  • 适合配置文件和设置

JSON 格式

  • 标准的数据交换格式
  • 支持嵌套对象和数组
  • 严格的语法规则
  • 广泛的编程语言支持

工具简介:INI 转 JSON 工具

INI 和 JSON 都是常用的配置文件格式。INI 格式简单易读,适合人工编辑;JSON 格式结构化强,适合程序处理。本工具提供两种格式的双向转换功能,帮助开发者在不同场景下选择合适的配置格式。

什么是INI 转 JSON 工具?

INI 转 JSON 用于在INI与JSON之间快速转换,输出可直接用于JSON场景。

如何使用

  1. 粘贴INI内容或输入参数。
  2. 选择输出为JSON并设置转换选项。
  3. 查看结果并复制或下载。

常见应用场景

  • INI 与 JSON 之间的格式迁移与对接
  • 将 INI 数据用于 JSON 生态或代码生成
  • 调试与验证转换是否符合规范

❓ 常见问题 FAQ

Q1:转换失败或结果为空?
A:请确认INI格式是否有效,必要时先格式化或清洗输入。

Q2:转换后顺序或缩进改变?
A:输出会遵循JSON语法规则,可能调整空白或键顺序。

Q3:如何批量处理?
A:建议分批转换以避免单次输入过大。

✨ 主要特性

  • 🔄 双向转换:支持 INI 转 JSON 和 JSON 转 INI
  • 语法验证:自动检测格式错误并提供详细提示
  • 🎨 格式美化:自动格式化输出结果,提升可读性
  • 📋 一键复制:转换结果可直接复制使用
  • 🔧 智能解析:支持注释、节(section)和类型转换

📖 使用示例

INI 转 JSON 示例

输入 INI:

# 应用程序配置
[app]
name = 工具迷
version = 1.0.0
debug = true
port = 3000

[database]
host = localhost
port = 5432
username = admin
password = secret123
ssl = false

[features]
multi_language = true
seo_friendly = true
responsive_design = true

输出 JSON:

{
  "app": {
    "name": "工具迷",
    "version": "1.0.0",
    "debug": true,
    "port": 3000
  },
  "database": {
    "host": "localhost",
    "port": 5432,
    "username": "admin",
    "password": "secret123",
    "ssl": false
  },
  "features": {
    "multi_language": true,
    "seo_friendly": true,
    "responsive_design": true
  }
}

JSON 转 INI 示例

输入 JSON:

{
  "server": {
    "host": "0.0.0.0",
    "port": 8080,
    "ssl": true
  },
  "logging": {
    "level": "info",
    "file": "/var/log/app.log"
  }
}

输出 INI:

[server]
host = 0.0.0.0
port = 8080
ssl = true

[logging]
level = info
file = /var/log/app.log

🎯 应用场景

1. 配置文件迁移

// 配置文件迁移工具
class ConfigMigrator {
  constructor() {
    this.supportedFormats = ['ini', 'json', 'yaml', 'toml'];
  }

  // 从 INI 迁移到 JSON
  migrateFromINI(iniContent, targetFormat = 'json') {
    try {
      // 解析 INI 内容
      const config = this.parseINI(iniContent);
      
      // 验证配置结构
      this.validateConfig(config);
      
      // 转换为目标格式
      switch (targetFormat) {
        case 'json':
          return JSON.stringify(config, null, 2);
        case 'yaml':
          return this.toYAML(config);
        default:
          throw new Error(`不支持的目标格式: ${targetFormat}`);
      }
    } catch (error) {
      throw new Error(`配置迁移失败: ${error.message}`);
    }
  }

  // 批量迁移配置文件
  batchMigrate(configFiles, targetFormat) {
    const results = [];
    
    for (const file of configFiles) {
      try {
        const result = this.migrateFromINI(file.content, targetFormat);
        results.push({
          filename: file.name,
          status: 'success',
          content: result
        });
      } catch (error) {
        results.push({
          filename: file.name,
          status: 'error',
          error: error.message
        });
      }
    }
    
    return results;
  }
}

// 使用示例
const migrator = new ConfigMigrator();
const iniConfig = `
[database]
host = localhost
port = 5432
name = myapp

[redis]
host = 127.0.0.1
port = 6379
`;

const jsonConfig = migrator.migrateFromINI(iniConfig, 'json');
console.log('迁移后的 JSON 配置:');
console.log(jsonConfig);

2. 环境配置管理

// 多环境配置管理器
class EnvironmentConfigManager {
  constructor() {
    this.environments = ['development', 'staging', 'production'];
    this.configCache = new Map();
  }

  // 加载环境配置
  loadEnvironmentConfig(env, format = 'ini') {
    const cacheKey = `${env}-${format}`;
    
    if (this.configCache.has(cacheKey)) {
      return this.configCache.get(cacheKey);
    }

    try {
      const configPath = `./config/${env}.${format}`;
      const configContent = this.readConfigFile(configPath);
      
      let parsedConfig;
      if (format === 'ini') {
        parsedConfig = this.parseINI(configContent);
      } else if (format === 'json') {
        parsedConfig = JSON.parse(configContent);
      }

      // 缓存配置
      this.configCache.set(cacheKey, parsedConfig);
      return parsedConfig;
    } catch (error) {
      throw new Error(`加载 ${env} 环境配置失败: ${error.message}`);
    }
  }

  // 合并配置
  mergeConfigs(baseConfig, envConfig) {
    return {
      ...baseConfig,
      ...envConfig,
      // 深度合并嵌套对象
      database: {
        ...baseConfig.database,
        ...envConfig.database
      },
      features: {
        ...baseConfig.features,
        ...envConfig.features
      }
    };
  }

  // 导出配置为不同格式
  exportConfig(config, format) {
    switch (format) {
      case 'ini':
        return this.toINI(config);
      case 'json':
        return JSON.stringify(config, null, 2);
      case 'env':
        return this.toEnvFile(config);
      default:
        throw new Error(`不支持的导出格式: ${format}`);
    }
  }
}

// 使用示例
const configManager = new EnvironmentConfigManager();

// 加载基础配置和环境特定配置
const baseConfig = configManager.loadEnvironmentConfig('base', 'ini');
const prodConfig = configManager.loadEnvironmentConfig('production', 'json');

// 合并配置
const finalConfig = configManager.mergeConfigs(baseConfig, prodConfig);

// 导出为不同格式
const iniOutput = configManager.exportConfig(finalConfig, 'ini');
const jsonOutput = configManager.exportConfig(finalConfig, 'json');

console.log('INI 格式配置:', iniOutput);
console.log('JSON 格式配置:', jsonOutput);

3. 配置文件验证和标准化

// 配置文件验证器
class ConfigValidator {
  constructor() {
    this.schemas = {
      database: {
        required: ['host', 'port', 'username'],
        types: {
          host: 'string',
          port: 'number',
          username: 'string',
          password: 'string',
          ssl: 'boolean'
        }
      },
      app: {
        required: ['name', 'version'],
        types: {
          name: 'string',
          version: 'string',
          debug: 'boolean',
          port: 'number'
        }
      }
    };
  }

  // 验证配置结构
  validateConfig(config) {
    const errors = [];

    for (const [section, sectionConfig] of Object.entries(config)) {
      const schema = this.schemas[section];
      if (!schema) {
        continue; // 跳过未定义的节
      }

      // 检查必需字段
      for (const requiredField of schema.required) {
        if (!(requiredField in sectionConfig)) {
          errors.push(`缺少必需字段: ${section}.${requiredField}`);
        }
      }

      // 检查字段类型
      for (const [field, value] of Object.entries(sectionConfig)) {
        const expectedType = schema.types[field];
        if (expectedType && typeof value !== expectedType) {
          errors.push(`类型错误: ${section}.${field} 应该是 ${expectedType},实际是 ${typeof value}`);
        }
      }
    }

    return {
      isValid: errors.length === 0,
      errors: errors
    };
  }

  // 标准化配置
  normalizeConfig(config) {
    const normalized = {};

    for (const [section, sectionConfig] of Object.entries(config)) {
      normalized[section] = {};
      
      for (const [key, value] of Object.entries(sectionConfig)) {
        // 标准化键名(转换为小写,用下划线分隔)
        const normalizedKey = key.toLowerCase().replace(/[^a-z0-9]/g, '_');
        
        // 标准化值
        let normalizedValue = value;
        if (typeof value === 'string') {
          // 尝试转换布尔值
          if (value.toLowerCase() === 'true') {
            normalizedValue = true;
          } else if (value.toLowerCase() === 'false') {
            normalizedValue = false;
          }
          // 尝试转换数字
          else if (!isNaN(value) && !isNaN(parseFloat(value))) {
            normalizedValue = parseFloat(value);
          }
        }
        
        normalized[section][normalizedKey] = normalizedValue;
      }
    }

    return normalized;
  }
}

// 使用示例
const validator = new ConfigValidator();

const config = {
  database: {
    host: "localhost",
    port: "5432", // 字符串形式的数字
    username: "admin"
    // 缺少 password
  },
  app: {
    name: "MyApp",
    version: "1.0.0",
    debug: "true" // 字符串形式的布尔值
  }
};

// 验证配置
const validation = validator.validateConfig(config);
if (!validation.isValid) {
  console.log('配置验证失败:');
  validation.errors.forEach(error => console.log(`- ${error}`));
}

// 标准化配置
const normalizedConfig = validator.normalizeConfig(config);
console.log('标准化后的配置:', normalizedConfig);

📐 格式对比

INI 格式特点

  • 简单易读:人类友好的格式,易于手工编辑
  • 节结构:使用 [section] 组织配置
  • 键值对key = value 格式
  • 注释支持:支持 #; 注释
  • 类型限制:主要支持字符串,需要手动类型转换

JSON 格式特点

  • 结构化:严格的数据结构,支持嵌套
  • 类型丰富:支持字符串、数字、布尔值、数组、对象
  • 标准格式:广泛的编程语言支持
  • 机器友好:易于程序解析和生成
  • 无注释:不支持注释(标准 JSON)

🔧 使用技巧

  1. 类型转换:工具会自动识别并转换 true/false 和数字
  2. 注释处理:INI 中的注释在转换为 JSON 时会被忽略
  3. 特殊字符:包含空格或等号的值会自动加引号
  4. 嵌套结构:JSON 的嵌套对象会转换为 INI 的多个节
  5. 验证检查:转换前后都会进行格式验证

🎓 学习要点

  • 理解 INI 和 JSON 格式的特点和适用场景
  • 掌握配置文件的结构设计原则
  • 学会选择合适的配置格式
  • 了解配置文件的版本管理和迁移策略

这个 INI 转 JSON 工具不仅是一个格式转换器,更是配置文件管理和迁移的好帮手!