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

如何将JSON转为DocumentAI的Document对象并解决序列化错误

问题解决:Document AI TextAnchor序列化失败及反向转换Document对象

错误原因

你直接将Document AI的TextAnchor proto对象赋值给了字典,而json.dumps只能序列化Python原生数据类型(如dict、list、str),无法处理Protobuf生成的自定义对象,因此抛出TypeError: Object of type TextAnchor is not JSON serializable。

解决方案

1. 先将TextAnchor转成可序列化的字典

使用Google Protobuf提供的MessageToDict方法,把TextAnchor对象转换为Python字典,这样就能正常被JSON序列化。

2. 正确实现Document对象的反向转换

修改后的JSON字符串可以通过google.protobuf.json_format.Parse方法解析回Document对象,部分SDK版本也支持直接使用documentai.Document.from_json()。

完整代码示例

from google.protobuf.json_format import MessageToDict, Parse
import json
import documentai

# 将原始Document转为JSON字典
doc_json_str = documentai.Document.to_json(result.document)
doc_dict = json.loads(doc_json_str)

# 提取TextAnchor并转为可序列化字典
target_field = result.document.pages[0].form_fields[0].field_value
text_anchor_dict = MessageToDict(target_field.text_anchor)

# 构造自定义entities
entities_list = [{"textAnchor": text_anchor_dict}]
doc_dict["entities"] = entities_list

# 将修改后的字典转回JSON字符串,再解析为Document对象
updated_doc_json_str = json.dumps(doc_dict)
updated_document = Parse(updated_doc_json_str, documentai.Document())

# 若你的DocumentAI版本支持from_json,也可以这样用:
# updated_document = documentai.Document.from_json(updated_doc_json_str)

关于反向转换函数

Document AI的Document类本身提供了to_json()方法,对应的反向转换可以通过两种方式实现:

  • 使用documentai.Document.from_json(json_str)(部分SDK版本支持,写法更简洁)
  • 使用Protobuf通用的google.protobuf.json_format.Parse(json_str, documentai.Document())(兼容性更强)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:22:42