8000 bpo-33927: Add support for same infile and outfile to json.tool by remilapeyre · Pull Request #7865 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

bpo-33927: Add support for same infile and outfile to json.tool #7865

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

Closed
Closed
Prev Previous commit
Next Next commit
Merge remote-tracking branch 'origin/master' into bugfix/json.tool-sa…
…me-infile-outfile
  • Loading branch information
Rémi Lapeyre committed Dec 26, 2018
commit e60698079eb3769c5b1ba5f1356dab07af6953f2
12 changes: 5 additions & 7 deletions Lib/json/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,12 @@ def main():
infile = options.infile or sys.stdin
sort_keys = options.sort_keys
json_lines = options.json_lines
with infile, outfile:
with infile:
try:
if json_lines:
objs = (json.loads(line) for line in infile)
objs = tuple(json.loads(line) for line in infile)
else:
objs = (json.load(infile), )
for obj in objs:
json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
outfile.write('\n')
except ValueError as e:
raise SystemExit(e)

Expand All @@ -50,8 +47,9 @@ def main():
except IOError as e:
parser.error(f"can't open '{options.outfile}': {str(e)}")
with outfile:
json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
outfile.write('\n')
for obj in objs:
json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
outfile.write('\n')


if __name__ == '__main__':
Expand Down
7 changes: 7 additions & 0 deletions Lib/test/test_json/test_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,13 @@ def test_unavailable_outfile(self):
self.assertEqual(out, b'')
self.assertIn(b"error: can't open '/bla/outfile': [Errno 2]", err)

def test_jsonlines(self):
args = sys.executable, '-m', 'json.tool', '--json-lines'
with Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) as proc:
out, err = proc.communicate(self.jsonlines_raw.encode())
self.assertEqual(out.splitlines(), self.jsonlines_expect.encode().splitlines())
self.assertEqual(err, b'')

def test_help_flag(self):
rc, out, err = assert_python_ok('-m', 'json.tool', '-h')
self.assertTrue(out.startswith(b'usage: '))
Expand Down
You are viewing a condensed version of this merge commit. You can view the full changes here.
0