FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

gh-132631: Fix json.tool when using --json-lines and a file as input by mpkocher · Pull Request #138961 · python/cpython · GitHub

/ cpython Public
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .py  (2) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
25 changes: 13 additions & 12 deletions Lib/json/tool.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -84,23 +84,23 @@ def main():

try:
if options.infile == '-':
infile = sys.stdin
in_f = sys.stdin.fileno()
else:
infile = open(options.infile, encoding='utf-8')
try:
in_f = options.infile

if options.outfile is None:
out_f = sys.stdout.fileno()
else:
out_f = options.outfile

with (open(in_f, 'r', encoding='utf-8') as infile,
open(out_f, 'w', encoding='utf-8') as outfile):

if options.json_lines:
objs = (json.loads(line) for line in infile)
else:
objs = (json.load(infile),)
finally:
if infile is not sys.stdin:
infile.close()
objs = [json.load(infile)]

if options.outfile is None:
outfile = sys.stdout
else:
outfile = open(options.outfile, 'w', encoding='utf-8')
with outfile:
if can_colorize(file=outfile):
t = get_theme(tty_file=outfile).syntax
for obj in objs:
Expand All @@ -111,6 +111,7 @@ def main():
for obj in objs:
json.dump(obj, outfile, **dump_args)
outfile.write('\n')

except ValueError as e:
raise SystemExit(e)

Expand Down
8 changes: 8 additions & 0 deletions Lib/test/test_json/test_tool.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,14 @@ def test_jsonlines(self):
self.assertEqual(process.stdout, self.jsonlines_expect)
self.assertEqual(process.stderr, '')

@force_not_colorized
def test_jsonlines_with_file(self):
infile = self._create_infile(self.jsonlines_raw)
args = sys.executable, '-m', self.module, '--json-lines', infile
process = subprocess.run(args, capture_output=True, text=True, check=True)
self.assertEqual(process.stdout, self.jsonlines_expect)
self.assertEqual(process.stderr, '')

def test_help_flag(self):
rc, out, err = assert_python_ok('-m', self.module, '-h',
PYTHON_COLORS='0')
Expand Down
Loading

Back | FazBrowse Home | New Git URL