You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将多级缩进TXT文件转换为JSON或扁平字典

将缩进式TXT配置文件转换为嵌套JSON或扁平字典

示例输入格式

key1=value1
key2
    key2_1=value2_1
    key2_2
        key2_2_1=value2_2_1
    key2_3=value2_3
key3=value3

期望的嵌套JSON输出

{
    "key1": "value1",
    "key2": {
        "key2_1": "value2_1",
        "key2_2": {
            "key2_2_1": "value2_2_1"
        },
        "key2_3": "value2_3"
    },
    "key3": "value3"
}

实现方案(Python脚本)

1. 转换为嵌套JSON

以下脚本支持单个文件转换,也可批量处理指定目录下的所有目标TXT文件,生成对应嵌套JSON文件:

import json
import os

INDENT_SPACES = 4  # 配置文件的缩进单位为4个空格

def parse_line(line):
    line = line.strip()
    if not line:
        return None, None, 0
    # 计算当前行的缩进层级
    indent = len(line) - len(line.lstrip(' '))
    level = indent // INDENT_SPACES
    # 拆分key和value
    if '=' in line:
        key, value = line.strip().split('=', 1)
        return key.strip(), value.strip(), level
    else:
        key = line.strip()
        return key, None, level

def parse_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    root = {}
    stack = [(root, -1)]  # 栈结构维护当前层级的字典
    
    for line in lines:
        key, value, level = parse_line(line)
        if key is None:
            continue
        
        # 回溯到当前层级的父字典
        while stack[-1][1] >= level:
            stack.pop()
        parent_dict = stack[-1][0]
        
        if value is not None:
            parent_dict[key] = value
        else:
            new_dict = {}
            parent_dict[key] = new_dict
            stack.append((new_dict, level))
    
    return root

def convert_to_nested_json(input_path, output_path=None):
    result = parse_file(input_path)
    if not output_path:
        output_path = os.path.splitext(input_path)[0] + '_nested.json'
    with open(output_path, 'w', encoding='utf-8') as f:
        json.dump(result, f, indent=INDENT_SPACES, ensure_ascii=False)
    print(f"已生成嵌套JSON文件: {output_path}")

# 单个文件转换示例,取消注释即可运行
# convert_to_nested_json('config.txt')

# 批量处理目录下所有TXT文件示例
def batch_convert_nested(input_dir):
    for filename in os.listdir(input_dir):
        if filename.endswith('.txt'):
            file_path = os.path.join(input_dir, filename)
            convert_to_nested_json(file_path)

# batch_convert_nested('./config_files')

2. 转换为扁平字典

如果需要将层级结构展平为父key.子key形式的扁平字典,可使用以下脚本:

import json
import os

INDENT_SPACES = 4

def parse_line(line):
    line = line.strip()
    if not line:
        return None, None, 0
    indent = len(line) - len(line.lstrip(' '))
    level = indent // INDENT_SPACES
    if '=' in line:
        key, value = line.strip().split('=', 1)
        return key.strip(), value.strip(), level
    else:
        key = line.strip()
        return key, None, level

def parse_to_flat_dict(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    flat_dict = {}
    key_stack = []
    
    for line in lines:
        key, value, level = parse_line(line)
        if key is None:
            continue
        
        # 调整key栈到当前层级
        while len(key_stack) > level:
            key_stack.pop()
        key_stack.append(key)
        
        if value is not None:
            flat_key = '.'.join(key_stack)
            flat_dict[flat_key] = value

    return flat_dict

def convert_to_flat_json(input_path, output_path=None):
    result = parse_to_flat_dict(input_path)
    if not output_path:
        output_path = os.path.splitext(input_path)[0] + '_flat.json'
    with open(output_path, 'w', encoding='utf-8') as f:
        json.dump(result, f, indent=INDENT_SPACES, ensure_ascii=False)
    print(f"已生成扁平JSON文件: {output_path}")

# 单个文件转换示例
# convert_to_flat_json('config.txt')

# 批量处理示例
def batch_convert_flat(input_dir):
    for filename in os.listdir(input_dir):
        if filename.endswith('.txt'):
            file_path = os.path.join(input_dir, filename)
            convert_to_flat_json(file_path)

# batch_convert_flat('./config_files')

使用说明

  • 根据实际配置文件的缩进空格数,调整INDENT_SPACES的值
  • 取消对应函数的注释即可运行单个或批量转换
  • 转换后的JSON文件会保存在原TXT文件同目录,文件名后缀为_nested.json或_flat.json

内容的提问来源于stack exchange,提问作者NigelBlainey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 21:15:43