Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions Lib/json/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import sys
from pathlib import Path

_SENTINEL = object()
Comment thread
ZeeD marked this conversation as resolved.

def main():
prog = 'python -m json.tool'
Expand Down Expand Up @@ -62,7 +63,7 @@ def main():
with options.infile as infile:
try:
if options.json_lines:
objs = (json.loads(line) for line in infile)
objs = (json.loads(line) if line.strip() else _SENTINEL for line in infile)
else:
objs = (json.load(infile),)

Expand All @@ -72,7 +73,8 @@ def main():
out = options.outfile.open('w', encoding='utf-8')
with out as outfile:
for obj in objs:
json.dump(obj, outfile, **dump_args)
if obj is not _SENTINEL:
json.dump(obj, outfile, **dump_args)
outfile.write('\n')
except ValueError as e:
raise SystemExit(e)
Expand Down
24 changes: 24 additions & 0 deletions Lib/test/test_json/test_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,24 @@ class TestTool(unittest.TestCase):
}
""")

jsonlines_emptylines_raw = textwrap.dedent("""\
{"foo":1}

{"bar":2}

""")

jsonlines_emptylines_expect = textwrap.dedent("""\
{
"foo": 1
}

{
"bar": 2
}

""")

def test_stdin_stdout(self):
args = sys.executable, '-m', 'json.tool'
process = subprocess.run(args, input=self.data, capture_output=True, text=True, check=True)
Expand Down Expand Up @@ -147,6 +165,12 @@ def test_jsonlines(self):
self.assertEqual(process.stdout, self.jsonlines_expect)
self.assertEqual(process.stderr, '')

def test_jsonlines_emptylines(self):
args = sys.executable, '-m', 'json.tool', '--json-lines'
process = subprocess.run(args, input=self.jsonlines_emptylines_raw, capture_output=True, text=True, check=True)
self.assertEqual(process.stdout, self.jsonlines_emptylines_expect)
self.assertEqual(process.stderr, '')

def test_help_flag(self):
rc, out, err = assert_python_ok('-m', 'json.tool', '-h')
self.assertEqual(rc, 0)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Let json.tool --json-lines handle empty rows