Skip to content

Commit a098b5d

Browse files
committed
json.tool: --compact identation option
1 parent 70cc07b commit a098b5d

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

Lib/json/tool.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ def main():
3535
const=None, help='Use compact mode.')
3636
group.add_argument('--tab', action='store_const', dest='indent',
3737
const='\t', help='Use tabs for indentation.')
38+
group.add_argument('--compact', action='store_true',
39+
help='Use most compact whitespace format.')
3840
parser.add_argument('--sort-keys', action='store_true',
3941
help='sort the output of dictionaries by key')
4042
options = parser.parse_args()
@@ -46,11 +48,15 @@ def main():
4648
except ValueError as e:
4749
raise SystemExit(e)
4850

51+
kwargs = {
52+
'indent': options.indent,
53+
'sort_keys': options.sort_keys,
54+
}
55+
if options.compact:
56+
kwargs['indent'] = None
57+
kwargs['separators'] = ',', ':'
4958
with options.outfile as outfile:
50-
json.dump(obj, outfile,
51-
indent=options.indent,
52-
sort_keys=options.sort_keys,
53-
)
59+
json.dump(obj, outfile, **kwargs)
5460
outfile.write('\n')
5561

5662

Lib/test/test_json/test_tool.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,3 +137,12 @@ def test_tab(self):
137137
json_stdout, err = proc.communicate(json_stdin)
138138
self.assertEqual(expect.splitlines(), json_stdout.splitlines())
139139
self.assertEqual(err, b'')
140+
141+
def test_compact(self):
142+
json_stdin = b'[ 1 ,\n 2]'
143+
expect = b'[1,2]'
144+
args = sys.executable, '-m', 'json.tool', '--compact'
145+
with Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) as proc:
146+
json_stdout, err = proc.communicate(json_stdin)
147+
self.assertEqual(expect.splitlines(), json_stdout.splitlines())
148+
self.assertEqual(err, b'')

0 commit comments

Comments
 (0)