从 google protobuf 对象中提取数据的正确方法是什么?

What's the proper way to extract data from a google protobuff object?

我以前从未遇到过这种集合或对象(它是对 Google-Cloud-Vision API 的请求的响应)。

我写了一个 class,它使用 API 并且正确地完成了我想要的。但是,我可以在响应中 extract/manipulate 数据的唯一方法是使用此模块:

from google.protobuf.json_format import MessageToJson 

我基本上是将 protobuff 序列化为一个字符串,然后使用正则表达式来获取我想要的数据。

一定有比这更好的方法。有什么建议么?我希望 API 响应给我一个 json dict 或 json dict 等等......我所能想到的只是将响应变成一个字符串。

这是 github 存储库中的文件: image_analyzer.py

提前谢谢大家。

内置的json模块会将字符串解析成字典,如json.loads(MessageToJson(response1))

您可以直接访问消息对象中的字段,例如:

response1 = vision_client.face_detection(image=image)
print(response1)
print(response1.face_annotations[0].detection_confidence)