Object of type InMemoryUploadedFile is not JSON serializable

2,026 阅读1分钟

- 1 错误信息

raise TypeError(f'Object of type {o.__class__.__name__} '
kombu.exceptions.EncodeError: Object of type InMemoryUploadedFile is not JSON serializable

- 2 错误原因

默认情况下,python只支持转换完整的默认数据类型(str,int,float,dict,list等)。 尝试转换InMemoryUploadedFile,转储函数不知道该如何处理。 需要做的是提供一种将数据转换为python支持的数据类型之一的方法

说人话就是你提供的类型python的转储函数不认识了需要你自己处理下

- 3 源码位置

django\core\serializers\json.py

class DjangoJSONEncoder(json.JSONEncoder):
    """
    JSONEncoder subclass that knows how to encode date/time, decimal types, and
    UUIDs.
    """
    def default(self, o):
        # See "Date Time String Format" in the ECMA-262 specification.
        if isinstance(o, datetime.datetime):
            r = o.isoformat()
            if o.microsecond:
                r = r[:23] + r[26:]
            if r.endswith('+00:00'):
                r = r[:-6] + 'Z'
            return r
        elif isinstance(o, datetime.date):
            return o.isoformat()
        elif isinstance(o, datetime.time):
            if is_aware(o):
                raise ValueError("JSON can't represent timezone-aware times.")
            r = o.isoformat()
            if o.microsecond:
                r = r[:12]
            return r
        elif isinstance(o, datetime.timedelta):
            return duration_iso_string(o)
        elif isinstance(o, (decimal.Decimal, uuid.UUID, Promise)):
            return str(o)
        else:
            return super().default(o)

4 解决方案

# 重写djangojsonencoder方法

from django.core.files.uploadedfile import InMemoryUploadedFile
from django.core.serializers.json import DjangoJSONEncoder

class MyJsonEncoder(DjangoJSONEncoder):
    def default(self, o):
        if isinstance(o, InMemoryUploadedFile):
            return o.read()
        return str(o)
        
# 使用 
# data 就是你要处理的数据
result = json.dumps(data, cls=MyJsonEncoder)