Skip to content

bpo-45929: extend json.tool --json-lines to ignore empty rows #29858

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
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
Next Next commit
ignore empty lines for json_lines files
  • Loading branch information
ZeeD authored Nov 29, 2021
commit 147f4ee67b1d2bcb1cc5ec50873dedfb68c98aff
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()

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