python - 如何将 'google.cloud.documentai.v1beta2.types.document.Document' 转换为 JSON?

标签 python json google-api google-api-python-client

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

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

感谢任何帮助!

最佳答案

我刚刚发现 google.cloud.documentai.v1beta2.types.document.Document 对象继承自 proto.Message,而它本身又继承自 proto.MessageMeta。您可以使用 proto.MessageMeta.to_json 函数将 Document 对象转换为 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)

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

关于python - 如何将 'google.cloud.documentai.v1beta2.types.document.Document' 转换为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63428499/

相关文章:

python - 在 Python 的列表中使用 abs()

python - math.pi 在 pygame 中未按预期工作

javascript - 从 url 下载 Google Drive 文件并通过帖子发送到后端

arrays - 震动 : Make Nested Make a nested array as part of main array

python - 客户端登录关闭 : Does this affect Gdata Library?

google-api - 网站管理员 API - 配额限制

Jquery Datetimepicker 到 Python Datetime

python - Intellisense 不适用于 Visual Studio Code 中的 Unreal

java - 使用Java和Jersey对以categoryID为键的类别进行JSON反序列化

json - Angular 2 - 如何使用来自外部文件的 JSON 数据填充局部变量