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

如何解决protobuf重复字段执行json.dumps时报DESCRIPTOR不存在的错误

问题原因

ad_group_ad.ad.responsive_search_ad.headlines和descriptions都是Protobuf定义的重复复合字段,类型是RepeatedCompositeContainer,不属于Python原生的列表/字典结构,Python内置的json.dumps无法识别这类Protobuf专属对象,因此抛出属性错误。

解决方案

方案1:使用Protobuf官方序列化工具(最简便,无需手动遍历)

谷歌Protobuf官方提供了现成的序列化工具,可以直接把Protobuf消息转成可被json.dumps处理的原生Python结构:

from google.protobuf.json_format import MessageToDict

def get_ad_full_details(ad_json, current_topics, ad_group_ad, ad):
    # 直接把ResponsiveSearchAd对象转成原生字典
    rsa_dict = MessageToDict(ad_group_ad.ad.responsive_search_ad)
    mandatory_data = {
        "ad_group_ad.ad.responsive_search_ad.headlines": rsa_dict.get("headlines", []),
        "ad_group_ad.ad.responsive_search_ad.descriptions": rsa_dict.get("descriptions", [])
    }
    ad_json["mandatory_data"] = mandatory_data

该方法会自动把所有Protobuf字段转成Python原生类型,后续直接调用json.dumps(ad_json)不会报错。

方案2:手动遍历提取text字段(仅需要text值时可选)

如果不需要其他字段,只需要每个条目的text值,直接遍历重复字段即可,每个元素都是Protobuf消息对象,直接调用.text属性取值即可:

def get_ad_full_details(ad_json, current_topics, ad_group_ad, ad):
    # 遍历提取所有headline的text值,转成普通字符串列表
    headlines = [item.text for item in ad_group_ad.ad.responsive_search_ad.headlines]
    # 同理处理descriptions
    descriptions = [item.text for item in ad_group_ad.ad.responsive_search_ad.descriptions]
    mandatory_data = {
        "ad_group_ad.ad.responsive_search_ad.headlines": headlines,
        "ad_group_ad.ad.responsive_search_ad.descriptions": descriptions
    }
    ad_json["mandatory_data"] = mandatory_data

如果之前遍历失败,大概率是属性名拼写错误,可以先打印单个字段元素print(ad_group_ad.ad.responsive_search_ad.headlines[0])确认实际属性名即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:39:03