From 6355a6d4f59eb220e05130d179beba7bb29c88af Mon Sep 17 00:00:00 2001 From: Lukas Hetzenecker Date: Tue, 23 Jun 2015 22:56:22 +0200 Subject: [PATCH] Fixed #25019 -- Added UUID support in DjangoJSONEncoder --- django/core/serializers/json.py | 5 ++++- tests/httpwrappers/tests.py | 6 ++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/django/core/serializers/json.py b/django/core/serializers/json.py index f67295edf9..764640465d 100644 --- a/django/core/serializers/json.py +++ b/django/core/serializers/json.py @@ -8,6 +8,7 @@ from __future__ import absolute_import, unicode_literals import datetime import decimal import json +import uuid import sys from django.core.serializers.base import DeserializationError @@ -86,7 +87,7 @@ def Deserializer(stream_or_string, **options): class DjangoJSONEncoder(json.JSONEncoder): """ - JSONEncoder subclass that knows how to encode date/time and decimal types. + 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. @@ -108,6 +109,8 @@ class DjangoJSONEncoder(json.JSONEncoder): return r elif isinstance(o, decimal.Decimal): return str(o) + elif isinstance(o, uuid.UUID): + return str(o) else: return super(DjangoJSONEncoder, self).default(o) diff --git a/tests/httpwrappers/tests.py b/tests/httpwrappers/tests.py index 3f641da89b..84d65ad801 100644 --- a/tests/httpwrappers/tests.py +++ b/tests/httpwrappers/tests.py @@ -6,6 +6,7 @@ import json import os import pickle import unittest +import uuid from django.core.exceptions import SuspiciousOperation from django.core.serializers.json import DjangoJSONEncoder @@ -480,6 +481,11 @@ class JsonResponseTests(SimpleTestCase): response = JsonResponse(['foo', 'bar'], safe=False) self.assertEqual(json.loads(response.content.decode()), ['foo', 'bar']) + def test_json_response_uuid(self): + u = uuid.uuid4() + response = JsonResponse(u, safe=False) + self.assertEqual(json.loads(response.content.decode()), str(u)) + def test_json_response_custom_encoder(self): class CustomDjangoJSONEncoder(DjangoJSONEncoder): def encode(self, o):