Skip to content

Commit 3c67514

Browse files
committed
Add --indent / --no-indent arguments to json.tool
From #201 which is being split into two pull requests. See http://bugs.python.org/issue29636
1 parent fadb45e commit 3c67514

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

Lib/json/tool.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@ def main():
2727
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
2828
default=sys.stdout,
2929
help='write the output of infile to outfile')
30+
group = parser.add_mutually_exclusive_group()
31+
group.add_argument('--indent', default=4, type=int,
32+
help='Indent level (number of spaces) for '
33+
'pretty-printing. Defaults to 4.')
34+
group.add_argument('--no-indent', action='store_const', dest='indent',
35+
const=None, help='Use compact mode.')
3036
parser.add_argument('--sort-keys', action='store_true',
3137
help='sort the output of dictionaries by key')
3238
options = parser.parse_args()
@@ -39,7 +45,10 @@ def main():
3945
raise SystemExit(e)
4046

4147
with options.outfile as outfile:
42-
json.dump(obj, outfile, sort_keys=options.sort_keys, indent=4)
48+
json.dump(obj, outfile,
49+
indent=options.indent,
50+
sort_keys=options.sort_keys,
51+
)
4352
outfile.write('\n')
4453

4554

Lib/test/test_json/test_tool.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,3 +105,26 @@ def test_sort_keys_flag(self):
105105
self.assertEqual(out.splitlines(),
106106
self.expect_without_sort_keys.encode().splitlines())
107107
self.assertEqual(err, b'')
108+
109+
def test_indent(self):
110+
json_stdin = b'[1, 2]'
111+
expect = textwrap.dedent('''\
112+
[
113+
1,
114+
2
115+
]
116+
''').encode()
117+
args = sys.executable, '-m', 'json.tool', '--indent', '2'
118+
with Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) as proc:
119+
json_stdout, err = proc.communicate(json_stdin)
120+
self.assertEqual(expect.splitlines(), json_stdout.splitlines())
121+
self.assertEqual(err, b'')
122+
123+
def test_no_indent(self):
124+
json_stdin = b'[1,\n2]'
125+
expect = b'[1, 2]'
126+
args = sys.executable, '-m', 'json.tool', '--no-indent'
127+
with Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) as proc:
128+
json_stdout, err = proc.communicate(json_stdin)
129+
self.assertEqual(expect.splitlines(), json_stdout.splitlines())
130+
self.assertEqual(err, b'')

0 commit comments

Comments
 (0)