Skip to content

Commit 053acf5

Browse files
committed
Fix dumps([], indent=2).
This addresses #26: `json5.dumps([], indent=2)` incorrectly returned '[\n ,\n]', when it should've returned '[]' (and the did the same thing for objects).
1 parent 63eaa05 commit 053acf5

2 files changed

Lines changed: 12 additions & 0 deletions

File tree

‎json5/lib.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,8 @@ def _dumps(obj, seen, **kwargs):
251251
# In Python3, we'd check if this was an abc.Sequence.
252252
# For now, just check for the attrs we need to iterate over the object.
253253
if hasattr(t, '__getitem__') and hasattr(t, '__iter__'):
254+
if not obj:
255+
return u'[]'
254256
return (u'[' + indent_str +
255257
item_sep.join([_dumps(el, seen, **kwargs) for el in obj]) +
256258
end_str + u']')
@@ -259,6 +261,9 @@ def _dumps(obj, seen, **kwargs):
259261

260262

261263
def _dump_dict(obj, seen, item_sep, kv_sep, indent_str, end_str, **kwargs):
264+
if not obj:
265+
return u'{}'
266+
262267
if kwargs.get('sort_keys', False):
263268
keys = sorted(obj.keys())
264269
else:

‎tests/lib_test.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,13 +279,20 @@ def test_indent(self):
279279
u'[\n1,\n2,\n3,\n]')
280280
self.assertEqual(json5.dumps([1, 2, 3], indent=0),
281281
u'[\n1,\n2,\n3,\n]')
282+
self.assertEqual(json5.dumps([], indent=2),
283+
u'[]')
282284
self.assertEqual(json5.dumps([1, 2, 3], indent=2),
283285
u'[\n 1,\n 2,\n 3,\n]')
284286
self.assertEqual(json5.dumps([1, 2, 3], indent=' '),
285287
u'[\n 1,\n 2,\n 3,\n]')
286288
self.assertEqual(json5.dumps([1, 2, 3], indent='++'),
287289
u'[\n++1,\n++2,\n++3,\n]')
288290

291+
self.assertEqual(json5.dumps({}, indent=2),
292+
u'{}')
293+
self.assertEqual(json5.dumps({'foo': 'bar', 'baz': 'quux'}, indent=2),
294+
u'{\n foo: "bar",\n baz: "quux",\n}')
295+
289296
def test_numbers(self):
290297
self.check(15, '15')
291298
self.check(1.0, '1.0')

0 commit comments

Comments
 (0)