diff --git a/Doc/library/json.rst b/Doc/library/json.rst --- a/Doc/library/json.rst +++ b/Doc/library/json.rst @@ -562,16 +562,17 @@ the last name-value pair for a given nam >>> weird_json = '{"x": 1, "x": 2, "x": 3}' >>> json.loads(weird_json) {'x': 3} The *object_pairs_hook* parameter can be used to alter this behavior. .. highlight:: bash +.. module:: json.tool .. _json-commandline: Command Line Interface ---------------------- The :mod:`json.tool` module provides a simple command line interface to validate and pretty-print JSON objects. @@ -581,16 +582,20 @@ specified, :attr:`sys.stdin` and :attr:` $ echo '{"json": "obj"}' | python -m json.tool { "json": "obj" } $ echo '{1.2:3.4}' | python -m json.tool Expecting property name enclosed in double quotes: line 1 column 2 (char 1) +.. versionchanged:: 3.5 + The output is now in the same order as the input. Use the + :option:`--sort-keys` option to sort the output of dictionaries by their + key. Command line options ^^^^^^^^^^^^^^^^^^^^ .. cmdoption:: infile The JSON file to be validated or pretty-printed:: @@ -608,11 +613,17 @@ Command line options If *infile* is not specified, read from :attr:`sys.stdin`. .. cmdoption:: outfile Write the output of the *infile* to the given *outfile*. Otherwise, write it to :attr:`sys.stdout`. +.. cmdoption:: --sort-keys + + Sort the output of dictionaries by their key. + + .. versionadded:: 3.5 + .. cmdoption:: -h, --help Show the help message. diff --git a/Doc/whatsnew/3.5.rst b/Doc/whatsnew/3.5.rst --- a/Doc/whatsnew/3.5.rst +++ b/Doc/whatsnew/3.5.rst @@ -206,16 +206,23 @@ inspect ipaddress --------- * :class:`ipaddress.IPv4Network` and :class:`ipaddress.IPv6Network` now accept an ``(address, netmask)`` tuple argument, so as to easily construct network objects from existing addresses. (Contributed by Peter Moody and Antoine Pitrou in :issue:`16531`.) +json +---- + +* The output of :mod:`json.tool` command line interface is now in the same + order as the input. Use the :option:`--sort-keys` option to sort the output + of dictionaries by their key (contributed by Berker Peksag in :issue:`21650`). + os -- * :class:`os.stat_result` now has a :attr:`~os.stat_result.st_file_attributes` attribute on Windows. (Contributed by Ben Hoyt in :issue:`21719`.) re -- diff --git a/Lib/json/tool.py b/Lib/json/tool.py --- a/Lib/json/tool.py +++ b/Lib/json/tool.py @@ -6,37 +6,45 @@ Usage:: { "json": "obj" } $ echo '{ 1.2:3.4}' | python -m json.tool Expecting property name enclosed in double quotes: line 1 column 3 (char 2) """ import argparse +import collections import json import sys def main(): prog = 'python -m json.tool' description = ('A simple command line interface for json module ' 'to validate and pretty-print JSON objects.') parser = argparse.ArgumentParser(prog=prog, description=description) parser.add_argument('infile', nargs='?', type=argparse.FileType(), 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('--sort-keys', action='store_true', default=False, + help='sort the output of dictionaries by their key') options = parser.parse_args() infile = options.infile or sys.stdin outfile = options.outfile or sys.stdout + sort_keys = options.sort_keys with infile: try: - obj = json.load(infile) + if sort_keys: + obj = json.load(infile) + else: + obj = json.load(infile, + object_pairs_hook=collections.OrderedDict) except ValueError as e: raise SystemExit(e) with outfile: - json.dump(obj, outfile, sort_keys=True, indent=4) + json.dump(obj, outfile, sort_keys=sort_keys, indent=4) outfile.write('\n') if __name__ == '__main__': main() diff --git a/Lib/test/test_json/test_tool.py b/Lib/test/test_json/test_tool.py --- a/Lib/test/test_json/test_tool.py +++ b/Lib/test/test_json/test_tool.py @@ -1,43 +1,66 @@ import os import sys import textwrap import unittest import subprocess from test import support from test.script_helper import assert_python_ok + class TestTool(unittest.TestCase): data = """ [["blorpie"],[ "whoops" ] , [ ],\t"d-shtaeou",\r"d-nthiouh", "i-vhbjkhnth", {"nifty":87}, {"morefield" :\tfalse,"field" :"yes"} ] """ + expect_without_sort_keys = textwrap.dedent("""\ + [ + [ + "blorpie" + ], + [ + "whoops" + ], + [], + "d-shtaeou", + "d-nthiouh", + "i-vhbjkhnth", + { + "nifty": 87 + }, + { + "field": "yes", + "morefield": false + } + ] + """) + expect = textwrap.dedent("""\ [ [ "blorpie" ], [ "whoops" ], [], "d-shtaeou", "d-nthiouh", "i-vhbjkhnth", { "nifty": 87 }, { - "field": "yes", - "morefield": false + "morefield": false, + "field": "yes" } ] """) def test_stdin_stdout(self): with subprocess.Popen( (sys.executable, '-m', 'json.tool'), stdin=subprocess.PIPE, stdout=subprocess.PIPE) as proc: @@ -70,8 +93,16 @@ class TestTool(unittest.TestCase): self.assertEqual(out, b'') self.assertEqual(err, b'') def test_help_flag(self): rc, out, err = assert_python_ok('-m', 'json.tool', '-h') self.assertEqual(rc, 0) self.assertTrue(out.startswith(b'usage: ')) self.assertEqual(err, b'') + + def test_sort_keys_flag(self): + infile = self._create_infile() + rc, out, err = assert_python_ok('-m', 'json.tool', '--sort-keys', infile) + self.assertEqual(rc, 0) + self.assertEqual(out.splitlines(), + self.expect_without_sort_keys.encode().splitlines()) + self.assertEqual(err, b'')