[Solved]-How to serialize(JSON) FileField in Django

13👍

It looks like you’re trying to serialize a reference to an InMemoryUploadedFile instance – if you just want to JSON serialize the data and not the whole class instance you could read the data.

Replace:

payload = {'doc_file': in_file}

With

payload = {'doc_file': in_file.read()}

You’ll want be sure to use chunks() if the data is large: https://docs.djangoproject.com/en/1.11/ref/files/uploads/#django.core.files.uploadedfile.UploadedFile.chunks

3👍

By default python only supports of converting a hand full of default datatypes (str, int, float, dict, list, etc.). You try to convert InMemoryUploadedFile, the dumps function doesn’t know how to handle that. What you need to do is provide a method to convert the data into one of the data types that python does supports.

class MyJsonEncoder(DjangoJSONEncoder):
    def default(self, o):
        if isinstance(o, InMemoryUploadedFile):
           return o.read()
        return str(o)


msg = json.dumps(payload, cls=MyJsonEncoder)
👤Du D.

Leave a comment