rserna2010
rserna2010

Reputation: 449

How do I encode a UUID to make it JSON serializable

I am using UUID instead of the default Django incremental IDs. However, now I get the following error:

file "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py",
line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable") TypeError: UUID('4fd5a26b452b4f62991d76488c71a554') is not JSON serializable

Here is my serializer file:

class ApplicationSerializer(serializers.ModelSerializer):

    class Meta:
        model = Application
        fields = ("id", "created_at", "merchant_uri", "api_key",
                  "status", 'owner_email', 'business_type', 'full_name',
                  'owner_phone_number', 'marketplace_name', 'domain_url',
                  'support_email', 'support_phone_number', 'postal_code',
                  'street_address', 'current_processor',
                  'current_monthly_volume')

Upvotes: 2

Views: 8784

Answers (2)

Javier Castellanos
Javier Castellanos

Reputation: 9874

You can use django-uuidfield, it serializes automatically.

Upvotes: 0

Kevin Brown-Silva
Kevin Brown-Silva

Reputation: 41671

This usually means you need to force your UUID to be serialized as a string, which can be done with the CharField. Some UUID field implementations for Django will do this by default, but it appears as though the one you are using will return the raw UUID object. By setting the field to a CharField, this will force it to be converted to a string.

class ApplicationSerializer(serializers.ModelSerializer):
    id = serializers.CharField(read_only=True)

    class Meta:
        model = Application
        fields = ("id", "created_at", "merchant_uri", "api_key",
                  "status", 'owner_email', 'business_type', 'full_name',
                  'owner_phone_number', 'marketplace_name', 'domain_url',
                  'support_email', 'support_phone_number', 'postal_code',
                  'street_address', 'current_processor',
                  'current_monthly_volume')

This will convert it to a string manually and will give you the output you are expecting.

Upvotes: 3

Related Questions