# HG changeset patch # User Wei-Cheng Pan # Date 1467198054 -28800 # Wed Jun 29 19:00:54 2016 +0800 # Node ID 9a86cb7b19b5f85f9cacb3a02efaae651f9fedde # Parent 8ec5a00e5d753565324537b5ded14c6ebcbea909 json: Add an option to bypass non-ASCII characters. diff --git a/Doc/library/json.rst b/Doc/library/json.rst --- a/Doc/library/json.rst +++ b/Doc/library/json.rst @@ -703,16 +703,22 @@ Command line options to :attr:`sys.stdout`. .. cmdoption:: --sort-keys Sort the output of dictionaries alphabetically by key. .. versionadded:: 3.5 +.. cmdoption:: --no-ensure-ascii + + Output non-ASCII characters as-is. + + .. versionadded:: 3.6 + .. cmdoption:: -h, --help Show the help message. .. rubric:: Footnotes .. [#rfc-errata] As noted in `the errata for RFC 7159 diff --git a/Lib/json/tool.py b/Lib/json/tool.py --- a/Lib/json/tool.py +++ b/Lib/json/tool.py @@ -22,29 +22,32 @@ def main(): '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 alphabetically by key') + parser.add_argument('--no-ensure-ascii', action='store_true', default=False, + help='output non-ASCII characters as-is') options = parser.parse_args() infile = options.infile or sys.stdin outfile = options.outfile or sys.stdout sort_keys = options.sort_keys + ensure_ascii = not options.no_ensure_ascii with infile: try: 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=sort_keys, indent=4) + json.dump(obj, outfile, ensure_ascii=ensure_ascii, 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 @@ -101,8 +101,16 @@ class TestTool(unittest.TestCase): 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'') + + def test_no_ensure_ascii_flag(self): + with subprocess.Popen( + (sys.executable, '-m', 'json.tool', '--no-ensure-ascii'), + stdin=subprocess.PIPE, stdout=subprocess.PIPE) as proc: + out, err = proc.communicate('"\u6e2c\u8a66"'.encode('UTF-8')) + self.assertEqual(out.splitlines(), '"\u6e2c\u8a66"\n'.encode('UTF-8').splitlines()) + self.assertEqual(err, None)