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

如何用Python将指定文本文件转换为目标JSON格式?

Python实现TXT到指定JSON格式的转换

需求说明

需要将以下input.txt文件内容转换为指定结构的output.json文件,此前尝试相关教程未找到适配方案。

输入文件input.txt内容:

Name 1, FeatureServer, thisIsALink, layer 1, layer 2
Name 2, FeatureServer, thisIsALink, layer 1
Name 3, MapServer, thisIsALink, layer 1, layer 2
Name 4, FeatureServer, thisIsALink, layer 1, layer 2
Name 5, FeatureServer, thisIsALink, layer 1, layer 2, layer 3

目标output.json格式:

{
    "Name 1": {
        "type": "FeatureServer",
        "url": "thisIsALink",
        "layer(s)": {
            "1": "layer 1",
            "2": "layer 2"
        }
    },
    "Name 2": {
        "type": "FeatureServer",
        "url": "thisIsALink",
        "layer(s)": {
            "1": "layer 1"
        }
    },
    "Name 3": {
        "type": "MapServer",
        "url": "thisIsALink",
        "layer(s)": {
            "1": "layer 1",
            "2": "layer 2"
        }
    },
    "Name 4": {
        "type": "FeatureServer",
        "url": "thisIsALink",
        "layer(s)": {
            "1": "layer 1",
            "2": "layer 2"
        }
    },
    "Name 5": {
        "type": "FeatureServer",
        "url": "thisIsALink",
        "layer(s)": {
            "1": "layer 1",
            "2": "layer 2",
            "3": "layer 3"
        }
    }
}

解决方案代码

import json

def txt_to_json(input_path, output_path):
    result = {}
    with open(input_path, 'r', encoding='utf-8') as f:
        for line in f:
            # 去除换行符并按逗号分割,同时清理每个元素的前后空格
            parts = [p.strip() for p in line.strip().split(',')]
            if not parts:
                continue
            # 提取基础字段
            name = parts[0]
            server_type = parts[1]
            url = parts[2]
            # 处理图层数据,生成指定键值对格式
            layers = parts[3:]
            layer_dict = {str(idx+1): layer for idx, layer in enumerate(layers)}
            # 组装当前条目
            result[name] = {
                "type": server_type,
                "url": url,
                "layer(s)": layer_dict
            }
    # 写入JSON文件,保留格式化缩进
    with open(output_path, 'w', encoding='utf-8') as f:
        json.dump(result, f, indent=4, ensure_ascii=False)

# 替换为你的实际文件路径后调用
txt_to_json('input.txt', 'output.json')

代码说明

  • 导入json模块完成JSON数据的序列化与写入
  • 逐行读取文本文件内容,对每行进行分割和空格清洗,避免多余空白影响数据提取
  • 拆分每行数据为名称、服务类型、链接、图层四个部分,其中图层部分可能有多个条目
  • 将图层列表转换为以数字字符串为键的字典,匹配目标JSON格式
  • 最后将整体结果写入JSON文件,通过indent=4保证输出格式美观易读

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 07:25:25