diff --git a/django/core/serializers/json.py b/django/core/serializers/json.py index b07aa33..01d44e6 100644 --- a/django/core/serializers/json.py +++ b/django/core/serializers/json.py @@ -24,6 +24,11 @@ class Serializer(PythonSerializer): internal_use_only = False def start_serialization(self): + if self.options.get('indent'): + # The default is (', ', ': '). To eliminate useless whitespaces + # after the comma at the end of each line, the representation is + # changed to (',', ': ') only if indent is used. + self.options['separators'] = (',', ': ') if json.__version__.split('.') >= ['2', '1', '3']: # Use JS strings to represent Python Decimal instances (ticket #16850) self.options.update({'use_decimal': False}) @@ -37,8 +42,6 @@ class Serializer(PythonSerializer): if self.options.get("indent"): self.stream.write("\n") self.stream.write("]") - if self.options.get("indent"): - self.stream.write("\n") def end_object(self, obj): # self._current has the field data diff --git a/tests/serializers/tests.py b/tests/serializers/tests.py index 07c220c..4ddbc5c 100644 --- a/tests/serializers/tests.py +++ b/tests/serializers/tests.py @@ -392,6 +392,32 @@ class JsonSerializerTestCase(SerializersTestBase, TestCase): ret_list.append(obj_dict["fields"][field_name]) return ret_list + +class TestJsonSerializerIndentation(TestCase): + def test_indentation_whitespace(self): + from django.core.serializers.json import Serializer + Score.objects.create(score=5.0) + Score.objects.create(score=6.0) + qset = Score.objects.all() + + s = Serializer() + self.assertEqual(s.serialize(qset, indent=2),"""[ +{ + "pk": 1, + "model": "serializers.score", + "fields": { + "score": 5.0 + } +}, +{ + "pk": 2, + "model": "serializers.score", + "fields": { + "score": 6.0 + } +} +]""") + class JsonSerializerTransactionTestCase(SerializersTransactionTestBase, TransactionTestCase): serializer_name = "json" fwd_ref_str = """[