Skip to content

bpo-29636: improve CLI of json.tool #9765

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
wants to merge 2 commits into from
Closed
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
10 changes: 10 additions & 0 deletions Doc/library/json.rst
Original file line number Diff line number Diff line change
Expand Up @@ -717,6 +717,16 @@ Command line options

.. versionadded:: 3.5

.. cmdoption:: --indent

Specify a string or integer to use as the indent, see :func:`json.dumps` for more information.

.. versionadded:: 3.8

.. cmdoption:: --no-ensure-ascii

Disable escaping of non-ascii characters, see :func:`json.dumps` for more information.

.. cmdoption:: --json-lines

Parse every input line as separate JSON object.
Expand Down
12 changes: 11 additions & 1 deletion Lib/json/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ def main():
help='a JSON file to be validated or pretty-printed')
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
help='write the output of infile to outfile')
parser.add_argument('--indent', default=4,
help='the indentation for pretty-print (int or str)')
parser.add_argument('--no-ensure-ascii', dest='ensure_ascii', action='store_false',
help='disable escaping of non-ASCII characters')
parser.add_argument('--sort-keys', action='store_true', default=False,
help='sort the output of dictionaries alphabetically by key')
parser.add_argument('--json-lines', action='store_true', default=False,
Expand All @@ -33,6 +37,11 @@ def main():
infile = options.infile or sys.stdin
outfile = options.outfile or sys.stdout
sort_keys = options.sort_keys
try:
indent = int(options.indent)
except ValueError:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if you use type in argparse you can remove this section

Copy link
Contributor Author

@wimglenn wimglenn Oct 11, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, then it will be impossible to pass tab character through to json dumps from the command-line, for example by using --indent=" ".

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ack!

# it is also possible to specify a string here
indent = options.indent
json_lines = options.json_lines
with infile, outfile:
try:
Expand All @@ -41,7 +50,8 @@ def main():
else:
objs = (json.load(infile), )
for obj in objs:
json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
json.dump(obj, outfile, sort_keys=sort_keys, indent=indent,
ensure_ascii=options.ensure_ascii)
outfile.write('\n')
except ValueError as e:
raise SystemExit(e)
Expand Down
30 changes: 30 additions & 0 deletions Lib/test/test_json/test_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,33 @@ def test_sort_keys_flag(self):
self.assertEqual(out.splitlines(),
self.expect_without_sort_keys.encode().splitlines())
self.assertEqual(err, b'')

def test_custom_indent_int(self):
infile = support.TESTFN
with open(infile, "w") as f:
self.addCleanup(os.remove, infile)
f.write('{"key":"val"}')
rc, out, err = assert_python_ok('-m', 'json.tool', '--indent=3', infile)
self.assertEqual(out.splitlines(),
[b'{', b' "key": "val"', b"}"])
self.assertEqual(err, b'')

def test_custom_indent_str(self):
infile = support.TESTFN
with open(infile, "w") as f:
self.addCleanup(os.remove, infile)
f.write('{"key":"val"}')
rc, out, err = assert_python_ok('-m', 'json.tool', '--indent', '\t', infile)
self.assertEqual(out.splitlines(),
[b'{', b'\t"key": "val"', b"}"])
self.assertEqual(err, b'')

def test_non_ascii(self):
infile = support.TESTFN
with open(infile, "w", encoding='utf-8') as f:
self.addCleanup(os.remove, infile)
f.write('{"key":"💩"}')
rc, out, err = assert_python_ok('-m', 'json.tool', '--no-ensure-ascii', infile)
self.assertEqual(out.splitlines(),
[b'{', b' "key": "\xf0\x9f\x92\xa9"', b"}"])
self.assertEqual(err, b'')
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Added ability to pass through `indent` and `ensure_ascii` options in
`json.tool` command-line interface.