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

生成文件并替换其中模板字符串,附指定JSON文件内容

我来给你详细说说怎么实现「用给定JSON数据替换模板文件字符串并生成目标文件」这个需求,用Python举个实操例子,你可以直接套用或者改成你熟悉的语言:

实现步骤与代码示例

首先,先准备你的模板文件(比如命名为template.txt),里面用自定义占位符标记需要替换的内容,示例模板如下:

=== Header Information ===
UUID: {{uuid}}
Production DateTime: {{productionDateTime}}
Application ID: {{app_id}}
Application Name: {{app_name}}

=== Correlation Context ===
Correlation ID: {{correlationId}}

接下来,用Python完成读取JSON、替换模板、生成文件的完整流程:

import json

# 1. 解析你提供的JSON数据(如果JSON是文件,直接读文件即可)
raw_json = '''{
    "header": {
        "uuid": "c578592a-a751-4993-9060-53f488597e59",
        "timestamp": 1522938800,
        "productionDateTime": "2018-04-05T14:33:20.000+00:00",
        "producers": {
            "operator": null,
            "application": {
                "com.example": {
                    "id": {"string": "1"},
                    "name": {"string": "Test"}
                }
            },
            "station": null,
            "equipment": null,
            "partner": null,
            "flow": null
        },
        "correlationContext": {
            "array": [{
                "correlationId": "98440498-3104-479e-9c99-f4449ba8f4b6",
                "correlationDateTime": {"string": "2018-04-05T14:..."}
            }]
        }
    }
}'''
data = json.loads(raw_json)

# 2. 从JSON中提取需要替换的字段,映射到模板占位符
replace_map = {
    "{{uuid}}": data["header"]["uuid"],
    "{{productionDateTime}}": data["header"]["productionDateTime"],
    "{{app_id}}": data["header"]["producers"]["application"]["com.example"]["id"]["string"],
    "{{app_name}}": data["header"]["producers"]["application"]["com.example"]["name"]["string"],
    "{{correlationId}}": data["header"]["correlationContext"]["array"][0]["correlationId"]
}

# 3. 读取模板文件内容
with open('template.txt', 'r', encoding='utf-8') as template_file:
    template_content = template_file.read()

# 4. 批量替换占位符
for placeholder, value in replace_map.items():
    template_content = template_content.replace(placeholder, value)

# 5. 生成最终目标文件
with open('output_result.txt', 'w', encoding='utf-8') as output_file:
    output_file.write(template_content)

额外说明:

  • 如果你的JSON数据是保存在本地文件(比如data.json),只需要把解析JSON的部分改成:
    with open('data.json', 'r', encoding='utf-8') as json_file:
        data = json.load(json_file)
    
  • 要是com.example这类应用键是动态的,不想硬编码,可以用list(data["header"]["producers"]["application"].values())[0]来获取第一个应用的信息
  • 占位符格式可以根据你的习惯自定义,只要和replace_map里的键对应上就好

运行这段代码后,你就能得到一份替换好所有内容的output_result.txt文件啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:10:36