You need to enable JavaScript to run this app. Python获取GCP Recommendations API嵌套值及OperationGroup报错解决
优惠活动
大模型
产品
解决方案
定价
更多

Python获取GCP Recommendations API嵌套值及OperationGroup报错解决

问题原因

你遇到的报错有两个核心问题:

  1. GCP Python SDK返回的响应不是JSON字典,是Protocol Buffer消息对象,不支持['key']的下标访问方式,必须用.字段名的属性方式取值
  2. 嵌套层级理解有误:operation_groups下的每个元素是OperationGroup对象,该对象下还有一层operations列表,你需要的resource_type字段是operations列表元素的属性,不是直接属于OperationGroup对象

修复后的代码

将你报错的循环段替换为以下代码即可正常提取字段:

for op_group in element.content.operation_groups:
    # 遍历operation_group下的所有操作
    for op in op_group.operations:
        # 用属性方式访问所需字段
        print(op.resource_type)
        print(op.action)
        print(op.resource)
        print(op.path)

可选扩展:转字典处理

如果你更习惯用字典格式操作数据,可以先把Proto对象转为Python字典:

# 导入Proto转字典的工具
from google.protobuf.json_format import MessageToDict

# 遍历每个element时转换
element_dict = MessageToDict(element._pb)
# 转字典后字段名会自动转为驼峰格式,按字典方式访问即可
for op_group in element_dict['content']['operationGroups']:
    for op in op_group['operations']:
        print(op['resourceType'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 13:45:04