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

Python读取带头部标记的JSON文本并提取指定头部下数据存入变量

解决方法

你只需要在原有打印逻辑的基础上,把原本打印的内容逐行拼接到空字符串变量中,再按需转换为JSON字典即可,以下是可直接运行的代码:

基础版(和你原有逻辑完全对齐,硬编码终止条件为header2)

import json

# 初始化空字符串存储原始JSON内容
payload_str = ""
with open("test.txt") as f:
    for line in f:
        if line.startswith('[header1]'):
            for line in f:
                if line.startswith("[header2]"):
                    break
                # 替换原有打印逻辑,将内容拼接到变量中
                payload_str += line

# 到这一步payload_str就是你要的原始JSON字符串内容,可直接打印验证
print(payload_str)

# 供requests模块使用建议转成Python字典,调用接口时直接传入json参数即可
payload = json.loads(payload_str)

通用优化版(无需硬编码下一个头部标识,自动匹配所有[headerX]格式的行作为终止条件,适配任意头部编号)

import json
import re

payload_str = ""
target_header = "[header1]"
# 匹配所有[header+数字]格式头部的正则规则
header_pattern = re.compile(r'^\[header\d+\]')

with open("test.txt") as f:
    for line in f:
        if line.strip() == target_header:
            for line in f:
                if header_pattern.match(line.strip()):
                    break
                payload_str += line

payload = json.loads(payload_str)

requests调用示例

import requests
response = requests.post("你的目标接口地址", json=payload)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:36:04