Work around 2.x/3.x json.dumps() return type fuzziness

This commit is contained in:
Tom Christie 2015-09-28 17:32:36 +01:00
parent 10dbf1316f
commit ec8098b7e2
2 changed files with 7 additions and 3 deletions

View File

@ -1544,7 +1544,11 @@ class JSONField(Field):
def to_representation(self, value): def to_representation(self, value):
if self.binary: if self.binary:
return json.dumps(value) value = json.dumps(value)
# On python 2.x the return type for json.dumps() is underspecified.
# On python 3.x json.dumps() returns unicode strings.
if isinstance(value, six.text_type):
value = bytes(value.encode('utf-8'))
return value return value

View File

@ -1562,7 +1562,7 @@ class TestBinaryJSONField(FieldValues):
Values for `JSONField` with binary=True. Values for `JSONField` with binary=True.
""" """
valid_inputs = [ valid_inputs = [
('{"a": 1, "3": null, "b": ["some", "list", true, 1.23]}', { (b'{"a": 1, "3": null, "b": ["some", "list", true, 1.23]}', {
'a': 1, 'a': 1,
'b': ['some', 'list', True, 1.23], 'b': ['some', 'list', True, 1.23],
'3': None '3': None
@ -1576,7 +1576,7 @@ class TestBinaryJSONField(FieldValues):
'a': 1, 'a': 1,
'b': ['some', 'list', True, 1.23], 'b': ['some', 'list', True, 1.23],
'3': None '3': None
}, '{"a": 1, "3": null, "b": ["some", "list", true, 1.23]}'), }, b'{"a": 1, "3": null, "b": ["some", "list", true, 1.23]}'),
] ]
field = serializers.JSONField(binary=True) field = serializers.JSONField(binary=True)