Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 39e4c4d

Browse files
committed
Issue #21650: Add an --sort-keys option to json.tool CLI.
1 parent ffd842e commit 39e4c4d

5 files changed

Lines changed: 63 additions & 3 deletions

File tree

Doc/library/json.rst

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -567,6 +567,7 @@ the last name-value pair for a given name::
567567
The *object_pairs_hook* parameter can be used to alter this behavior.
568568

569569
.. highlight:: bash
570+
.. module:: json.tool
570571

571572
.. _json-commandline:
572573

@@ -586,6 +587,10 @@ specified, :attr:`sys.stdin` and :attr:`sys.stdout` will be used respectively::
586587
$ echo '{1.2:3.4}' | python -m json.tool
587588
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
588589

590+
.. versionchanged:: 3.5
591+
The output is now in the same order as the input. Use the
592+
:option:`--sort-keys` option to sort the output of dictionaries
593+
alphabetically by key.
589594

590595
Command line options
591596
^^^^^^^^^^^^^^^^^^^^
@@ -613,6 +618,12 @@ Command line options
613618
Write the output of the *infile* to the given *outfile*. Otherwise, write it
614619
to :attr:`sys.stdout`.
615620

621+
.. cmdoption:: --sort-keys
622+
623+
Sort the output of dictionaries alphabetically by key.
624+
625+
.. versionadded:: 3.5
626+
616627
.. cmdoption:: -h, --help
617628

618629
Show the help message.

Doc/whatsnew/3.5.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,14 @@ ipaddress
211211
network objects from existing addresses. (Contributed by Peter Moody
212212
and Antoine Pitrou in :issue:`16531`.)
213213

214+
json
215+
----
216+
217+
* The output of :mod:`json.tool` command line interface is now in the same
218+
order as the input. Use the :option:`--sort-keys` option to sort the output
219+
of dictionaries alphabetically by key. (Contributed by Berker Peksag in
220+
:issue:`21650`.)
221+
214222
os
215223
--
216224

Lib/json/tool.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
1212
"""
1313
import argparse
14+
import collections
1415
import json
1516
import sys
1617

@@ -24,17 +25,24 @@ def main():
2425
help='a JSON file to be validated or pretty-printed')
2526
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
2627
help='write the output of infile to outfile')
28+
parser.add_argument('--sort-keys', action='store_true', default=False,
29+
help='sort the output of dictionaries alphabetically by key')
2730
options = parser.parse_args()
2831

2932
infile = options.infile or sys.stdin
3033
outfile = options.outfile or sys.stdout
34+
sort_keys = options.sort_keys
3135
with infile:
3236
try:
33-
obj = json.load(infile)
37+
if sort_keys:
38+
obj = json.load(infile)
39+
else:
40+
obj = json.load(infile,
41+
object_pairs_hook=collections.OrderedDict)
3442
except ValueError as e:
3543
raise SystemExit(e)
3644
with outfile:
37-
json.dump(obj, outfile, sort_keys=True, indent=4)
45+
json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
3846
outfile.write('\n')
3947

4048

Lib/test/test_json/test_tool.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from test import support
77
from test.script_helper import assert_python_ok
88

9+
910
class TestTool(unittest.TestCase):
1011
data = """
1112
@@ -15,7 +16,7 @@ class TestTool(unittest.TestCase):
1516
:"yes"} ]
1617
"""
1718

18-
expect = textwrap.dedent("""\
19+
expect_without_sort_keys = textwrap.dedent("""\
1920
[
2021
[
2122
"blorpie"
@@ -37,6 +38,28 @@ class TestTool(unittest.TestCase):
3738
]
3839
""")
3940

41+
expect = textwrap.dedent("""\
42+
[
43+
[
44+
"blorpie"
45+
],
46+
[
47+
"whoops"
48+
],
49+
[],
50+
"d-shtaeou",
51+
"d-nthiouh",
52+
"i-vhbjkhnth",
53+
{
54+
"nifty": 87
55+
},
56+
{
57+
"morefield": false,
58+
"field": "yes"
59+
}
60+
]
61+
""")
62+
4063
def test_stdin_stdout(self):
4164
with subprocess.Popen(
4265
(sys.executable, '-m', 'json.tool'),
@@ -75,3 +98,11 @@ def test_help_flag(self):
7598
self.assertEqual(rc, 0)
7699
self.assertTrue(out.startswith(b'usage: '))
77100
self.assertEqual(err, b'')
101+
102+
def test_sort_keys_flag(self):
103+
infile = self._create_infile()
104+
rc, out, err = assert_python_ok('-m', 'json.tool', '--sort-keys', infile)
105+
self.assertEqual(rc, 0)
106+
self.assertEqual(out.splitlines(),
107+
self.expect_without_sort_keys.encode().splitlines())
108+
self.assertEqual(err, b'')

Misc/NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,8 @@ Core and Builtins
183183
Library
184184
-------
185185

186+
- Issue #21650: Add an `--sort-keys` option to json.tool CLI.
187+
186188
- Issues #814253, #9179: Group references and conditional group references now
187189
work in lookbehind assertions in regular expressions.
188190

0 commit comments

Comments
 (0)