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

如何从多图片请求响应中提取event为result的JSON行

提取响应中图片请求的result JSON行方案

基础处理(基于你现有的分割逻辑)

直接在现有代码基础上延伸,核心是过滤无效行、提取JSON片段、筛选event为result的项:

import json

def get_img_url_from_response(self, response):
    response_content = response.content.decode("utf-8")
    response_list = response_content.split('\n')
    result_jsons = []
    
    for line in response_list:
        # 清理行首尾空白,跳过空行
        line = line.strip()
        if not line:
            continue
        # 从日志行中提取JSON部分(定位第一个{到最后一个}的区间)
        start_pos = line.find('{')
        end_pos = line.rfind('}')
        if start_pos == -1 or end_pos == -1:
            continue
        json_str = line[start_pos:end_pos+1]
        # 解析JSON并筛选目标事件
        try:
            data = json.loads(json_str)
            if data.get("event") == "result":
                result_jsons.append(data)
        except json.JSONDecodeError:
            # 跳过解析失败的无效行
            continue
    
    # 若每个图片请求对应多条result,需保留最后一条(假设有request_id这类唯一标识)
    # 可通过字典去重:
    # request_map = {}
    # for item in result_jsons:
    #     req_id = item.get("request_id")
    #     if req_id:
    #         request_map[req_id] = item
    # result_jsons = list(request_map.values())
    
    return result_jsons

更优的逐行处理方案(适合大响应场景)

如果响应内容体积较大,一次性分割成列表会占用过多内存,直接逐行迭代处理更高效:

import json

def get_img_url_from_response(self, response):
    result_jsons = []
    # 用splitlines()自动适配不同系统换行符,逐行处理
    for line in response.content.decode("utf-8").splitlines():
        line = line.strip()
        if not line:
            continue
        start_pos = line.find('{')
        end_pos = line.rfind('}')
        if start_pos == -1 or end_pos == -1:
            continue
        json_str = line[start_pos:end_pos+1]
        try:
            data = json.loads(json_str)
            if data.get("event") == "result":
                result_jsons.append(data)
        except json.JSONDecodeError:
            continue
    
    # 按请求去重保留最后一条的逻辑同上
    return result_jsons

关键细节

  • 日志行带前缀,必须先提取{}包裹的JSON片段,不能直接解析整行
  • 加入try-except捕获JSON解析错误,避免脏数据导致程序崩溃
  • 如果每个图片请求有唯一标识(如request_id),用字典记录最后一条result,就能确保每个请求只保留最终结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:05:27