Skip to content

Commit 3dd02d6

Browse files
committed
#10019: Fix regression relative to 2.6: add newlines if indent=0
Patch by Amaury Forgeot d'Arc, updated by Sando Tosi.
1 parent abdeeff commit 3dd02d6

File tree

4 files changed

+23
-4
lines changed

4 files changed

+23
-4
lines changed

Doc/library/json.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,9 +135,9 @@ Basic Usage
135135
using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
136136

137137
If *indent* is a non-negative integer, then JSON array elements and object
138-
members will be pretty-printed with that indent level. An indent level of 0
139-
will only insert newlines. ``None`` (the default) selects the most compact
140-
representation.
138+
members will be pretty-printed with that indent level. An indent level of 0,
139+
or negative, will only insert newlines. ``None`` (the default) selects the
140+
most compact representation.
141141

142142
If *separators* is an ``(item_separator, dict_separator)`` tuple, then it
143143
will be used instead of the default ``(', ', ': ')`` separators. ``(',',

Lib/json/encoder.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ def floatstr(o, allow_nan=self.allow_nan,
233233

234234

235235
if (_one_shot and c_make_encoder is not None
236-
and not self.indent):
236+
and self.indent is None):
237237
_iterencode = c_make_encoder(
238238
markers, self.default, _encoder, self.indent,
239239
self.key_separator, self.item_separator, self.sort_keys,

Lib/json/tests/test_indent.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import json
44
import textwrap
5+
from io import StringIO
56

67
class TestIndent(TestCase):
78
def test_indent(self):
@@ -39,3 +40,18 @@ def test_indent(self):
3940
self.assertEqual(h1, h)
4041
self.assertEqual(h2, h)
4142
self.assertEqual(d2, expect)
43+
44+
def test_indent0(self):
45+
h = {3: 1}
46+
def check(indent, expected):
47+
d1 = json.dumps(h, indent=indent)
48+
self.assertEqual(d1, expected)
49+
50+
sio = StringIO()
51+
json.dump(h, sio, indent=indent)
52+
self.assertEqual(sio.getvalue(), expected)
53+
54+
# indent=0 should emit newlines
55+
check(0, '{\n"3": 1\n}')
56+
# indent=None is more compact
57+
check(None, '{"3": 1}')

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,9 @@ Core and Builtins
5151
Library
5252
-------
5353

54+
- Issue #10019: Fixed regression in json module where an indent of 0 stopped
55+
adding newlines and acted instead like 'None'.
56+
5457
- Issue #5162: Treat services like frozen executables to allow child spawning
5558
from multiprocessing.forking on Windows.
5659

0 commit comments

Comments
 (0)