JSONEncoder: ensure empty listlikes remain lists, not dicts (#6794)

This commit is contained in:
Aarni Koskela 2019-07-09 13:41:05 +03:00 committed by Tom Christie
parent 7915485c0d
commit 5c922fb39d
2 changed files with 10 additions and 1 deletions

View File

@ -57,8 +57,9 @@ class JSONEncoder(json.JSONEncoder):
'You should be using a schema renderer instead for this view.' 'You should be using a schema renderer instead for this view.'
) )
elif hasattr(obj, '__getitem__'): elif hasattr(obj, '__getitem__'):
cls = (list if isinstance(obj, (list, tuple)) else dict)
try: try:
return dict(obj) return cls(obj)
except Exception: except Exception:
pass pass
elif hasattr(obj, '__iter__'): elif hasattr(obj, '__iter__'):

View File

@ -8,6 +8,7 @@ from django.utils.timezone import utc
from rest_framework.compat import coreapi from rest_framework.compat import coreapi
from rest_framework.utils.encoders import JSONEncoder from rest_framework.utils.encoders import JSONEncoder
from rest_framework.utils.serializer_helpers import ReturnList
class MockList: class MockList:
@ -93,3 +94,10 @@ class JSONEncoderTests(TestCase):
""" """
foo = MockList() foo = MockList()
assert self.encoder.default(foo) == [1, 2, 3] assert self.encoder.default(foo) == [1, 2, 3]
def test_encode_empty_returnlist(self):
"""
Tests encoding an empty ReturnList
"""
foo = ReturnList(serializer=None)
assert self.encoder.default(foo) == []