– 1 Error information

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

– 2 Error cause

By default, Python only supports converting full default data types (STR, int, float, dict, list, etc.). Trying to convert InMemoryUploadedFile, the dump function does not know what to do. All you need to do is provide a way to convert the data to one of the data types supported by Python

The python dump function is the type you provide and you need to handle it yourself

– 3 Source code location

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)
Copy the code

4 Solutions

# Override the djangojsonencoder method

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)
        
# use
# data is the data you want to process
result = json.dumps(data, cls=MyJsonEncoder)
Copy the code