close

[Solved] TypeError: Python object is not JSON serializable

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error TypeError: Python object is not JSON serializable in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How TypeError: Python object is not JSON serializable Error Occurs?

Today I get the following error TypeError: Python object is not JSON serializable in python.

How To Solve TypeError: Python object is not JSON serializable Error ?

  1. How To Solve TypeError: Python object is not JSON serializable Error ?

    To Solve TypeError: Python object is not JSON serializable Error The __dict__ gives all the attributes of the instance, but you don't want all that extra baggage – for the purposes of serialization, you are only interested in the fields.

  2. TypeError: Python object is not JSON serializable

    To Solve TypeError: Python object is not JSON serializable Error The __dict__ gives all the attributes of the instance, but you don't want all that extra baggage – for the purposes of serialization, you are only interested in the fields.

Solution 1

The __dict__ gives all the attributes of the instance, but you don’t want all that extra baggage – for the purposes of serialization, you are only interested in the fields.

Your model does not contain anything special so the built-in helper function model_to_dict should be enough for your needs:

import json
from django.forms.models import model_to_dict

oi = OrgInvite.objects.get(token=100) 
oi_dict = model_to_dict(oi)
oi_serialized = json.dumps(oi_dict)

Your example was simple, only containing CharFieldBooleanField, and ForeignKey all of which we can dump to json trivially.

For more complicated models, you might consider writing your own serializer. In this case, I recommend using the popular django-rest-framework which does all the work for you.

from rest_framework import serializers

class OrgInviteSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrgInvite
        fields = '__all__'

Solution 2

If you do invite.__dict__, it’s going to give you a dictionary of all data related to one invite object. However, the dict’s values are not necessarily primitive types, but objects as well(ModelState is just one of them). Serializing that would not only not working because json doesn’t accept python objects, but you could also serialize a lot of meta data that’s not used.

Check out json official website to see what data types are json serializable. The fix would be either using django model serializer, or manually create a dict that in compliance to json format.

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read