跳到内容
🛠️ToolsShed

INI to JSON

将 INI 配置文件转换为 JSON 格式,支持双向转换。

关于此工具

INI文件是Windows系统和传统软件中常用的简单易读的配置文件格式。在将传统配置系统与期望JSON输入的现代Web应用程序或API集成时,INI和JSON格式之间的转换至关重要。此工具可以即时完成转换,消除手工转录错误,节省开发时间。

要使用此工具,请将INI文件粘贴到输入编辑器中,然后点击"转换为JSON"以查看格式化的JSON输出;或粘贴JSON并点击"转换为INI"以反向转换。该工具保留了数据的结构和层级——部分变成JSON对象,键值对变成属性。常见用途包括升级应用程序时迁移配置文件、为云部署格式化设置,以及为需要JSON输入的API提交准备数据。

常见问题

代码实现

import configparser
import json

def ini_to_json(ini_text: str) -> dict:
    config = configparser.ConfigParser()
    config.read_string(ini_text)
    result = {}
    for section in config.sections():
        result[section] = dict(config[section])
    # Top-level keys (DEFAULT section workaround)
    for key, value in config.defaults().items():
        result[key] = value
    return result

ini_text = """
[database]
host = localhost
port = 5432
name = mydb
"""

data = ini_to_json(ini_text)
print(json.dumps(data, indent=2))

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.