Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Work around 2.x/3.x json.dumps() return type fuzziness
  • Loading branch information
lovelydinosaur committed Sep 28, 2015
commit ec8098b7e2b69e51c1a3196c20d11b253f914926
6 changes: 5 additions & 1 deletion rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1544,7 +1544,11 @@ def to_internal_value(self, data):

def to_representation(self, value):
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


Expand Down
4 changes: 2 additions & 2 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1562,7 +1562,7 @@ class TestBinaryJSONField(FieldValues):
Values for `JSONField` with binary=True.
"""
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,
'b': ['some', 'list', True, 1.23],
'3': None
Expand All @@ -1576,7 +1576,7 @@ class TestBinaryJSONField(FieldValues):
'a': 1,
'b': ['some', 'list', True, 1.23],
'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)

Expand Down