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

Azure Document Intelligence(2024预构建发票模型)JSON序列化报错求助

问题

使用Azure Document Intelligence 2024版本预构建发票模型处理PDF文件后,第一个print语句可正常打印转换为字典的invoiceResult结果,但执行第二个print语句调用json.dumps时,抛出错误:TypeError: Object of type DocumentPage is not JSON serializable。

相关代码:

document_intelligence_client = DocumentIntelligenceClient(endpoint=endpoint, credential=AzureKeyCredential(key)) 
poller = document_intelligence_client.begin_analyze_document("prebuilt-invoice", body=myContents, locale="en-US") 
invoiceResult: AnalyzeResult = poller.result() 
invoiceResultDict = dict(invoiceResult) 
print((invoiceResultDict))
print(json.dumps(invoiceResultDict))

解决方案

问题核心是dict(invoiceResult)仅做了浅层转换,invoiceResult中的嵌套对象(比如DocumentPage这类Azure SDK返回的自定义类实例)并未被转为可JSON序列化的普通字典,导致json.dumps无法处理。

方法一:使用SDK内置的to_dict()方法(推荐)

Azure Document Intelligence的AnalyzeResult对象提供了to_dict()方法,可递归将整个对象结构转换成完全可序列化的字典:

document_intelligence_client = DocumentIntelligenceClient(endpoint=endpoint, credential=AzureKeyCredential(key)) 
poller = document_intelligence_client.begin_analyze_document("prebuilt-invoice", body=myContents, locale="en-US") 
invoiceResult: AnalyzeResult = poller.result() 
# 替换dict()为to_dict()做深度转换
invoiceResultDict = invoiceResult.to_dict() 
print(invoiceResultDict)
print(json.dumps(invoiceResultDict))

方法二:自定义JSON编码器

如果需要更灵活的序列化控制,可自定义编码器处理SDK中的自定义类型:

import json
from azure.ai.documentintelligence.models import DocumentPage, DocumentLine, DocumentWord

class DocIntelligenceJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        # 对SDK返回的自定义类实例调用to_dict()
        if hasattr(obj, 'to_dict'):
            return obj.to_dict()
        return super().default(obj)

# 原代码保留,序列化时指定自定义编码器
document_intelligence_client = DocumentIntelligenceClient(endpoint=endpoint, credential=AzureKeyCredential(key)) 
poller = document_intelligence_client.begin_analyze_document("prebuilt-invoice", body=myContents, locale="en-US") 
invoiceResult: AnalyzeResult = poller.result() 
invoiceResultDict = dict(invoiceResult) 
print(invoiceResultDict)
print(json.dumps(invoiceResultDict, cls=DocIntelligenceJSONEncoder))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 18:04:59