如何将“ google.cloud.documentai.v1beta2.types.document.Document”转换为JSON?

问题描述

我正在使用Google Cloud Document AI的Form Parser API。在向API提出请求之后,我得到了类型为google.cloud.documentai.v1beta2.types.document.Document的响应。我尝试使用json.dumps()将其写入JSON,但它给出了JSONDecodeError,因为JSON.dumps()不知道如何序列化google.cloud.documentai.v1beta2.types.document.Document类型的对象。

我很困惑如何将其转换为JSON

感谢任何帮助!

解决方法

我解决了我的问题。

基本上,您必须编写一个探索Document对象的函数,然后自己通过代码组装整个JSON。

,

我刚刚发现 google.cloud.documentai.v1beta2.types.document.Document 对象继承自 proto.Message,而 proto.MessageMeta 本身继承自 proto.MessageMeta.to_json。您可以使用 import json from google.cloud.documentai_v1beta3 import Document json_string = Document.to_json(document) dict_obj = json.loads(json_string) with open("document.json",mode='w') as my_file: json.dump(dict_obj,my_file) 函数将 Document 对象转换为 json 字符串,如下所示:

proto.Message

{{1}} 的源代码有点难找,所以在这里:https://github.com/googleapis/proto-plus-python/blob/cfd5b6caca3fa9add89d8c69ea620505dd90dd7c/proto/message.py#L330