From 3e34005b1b4a9a447e3b3fd76e71f0c73d530414 Mon Sep 17 00:00:00 2001 From: Claude Paroz Date: Sat, 31 Aug 2013 15:05:17 +0200 Subject: [PATCH] Fixed #13182 -- Prevented trailing spaces in indented json output MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Thanks Stéphane Raimbault for the report and the initial patch. --- django/core/serializers/json.py | 3 +++ tests/serializers/tests.py | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/django/core/serializers/json.py b/django/core/serializers/json.py index b07aa3392c..8ea0b0815e 100644 --- a/django/core/serializers/json.py +++ b/django/core/serializers/json.py @@ -31,6 +31,9 @@ class Serializer(PythonSerializer): self.json_kwargs = self.options.copy() self.json_kwargs.pop('stream', None) self.json_kwargs.pop('fields', None) + if self.options.get('indent'): + # Prevent trailing spaces + self.json_kwargs['separators'] = (',', ': ') self.stream.write("[") def end_serialization(self): diff --git a/tests/serializers/tests.py b/tests/serializers/tests.py index 07c220c52e..67e053bcd2 100644 --- a/tests/serializers/tests.py +++ b/tests/serializers/tests.py @@ -392,6 +392,31 @@ class JsonSerializerTestCase(SerializersTestBase, TestCase): ret_list.append(obj_dict["fields"][field_name]) return ret_list + def test_indentation_whitespace(self): + Score.objects.create(score=5.0) + Score.objects.create(score=6.0) + qset = Score.objects.all() + + s = serializers.json.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 = """[