Skip to content

Commit e0f148e

Browse files
authored
bpo-33684: json.tool: Use utf-8 for infile and outfile. (GH-17460)
(cherry picked from commit 808769f) Co-authored-by: Inada Naoki <songofacandy@gmail.com>
1 parent 55a7046 commit e0f148e

File tree

3 files changed

+22
-5
lines changed

3 files changed

+22
-5
lines changed

Lib/json/tool.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@ def main():
2020
description = ('A simple command line interface for json module '
2121
'to validate and pretty-print JSON objects.')
2222
parser = argparse.ArgumentParser(prog=prog, description=description)
23-
parser.add_argument('infile', nargs='?', type=argparse.FileType(),
23+
parser.add_argument('infile', nargs='?', type=argparse.FileType(encoding="utf-8"),
2424
help='a JSON file to be validated or pretty-printed')
25-
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
25+
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w', encoding="utf-8"),
2626
help='write the output of infile to outfile')
2727
parser.add_argument('--sort-keys', action='store_true', default=False,
2828
help='sort the output of dictionaries alphabetically by key')

Lib/test/test_json/test_tool.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,11 @@ def test_stdin_stdout(self):
6767
self.assertEqual(out.splitlines(), self.expect.encode().splitlines())
6868
self.assertEqual(err, b'')
6969

70-
def _create_infile(self):
70+
def _create_infile(self, data=None):
7171
infile = support.TESTFN
72-
with open(infile, "w") as fp:
72+
with open(infile, "w", encoding="utf-8") as fp:
7373
self.addCleanup(os.remove, infile)
74-
fp.write(self.data)
74+
fp.write(data or self.data)
7575
return infile
7676

7777
def test_infile_stdout(self):
@@ -81,6 +81,21 @@ def test_infile_stdout(self):
8181
self.assertEqual(out.splitlines(), self.expect.encode().splitlines())
8282
self.assertEqual(err, b'')
8383

84+
def test_non_ascii_infile(self):
85+
data = '{"msg": "\u3053\u3093\u306b\u3061\u306f"}'
86+
expect = textwrap.dedent('''\
87+
{
88+
"msg": "\\u3053\\u3093\\u306b\\u3061\\u306f"
89+
}
90+
''').encode()
91+
92+
infile = self._create_infile(data)
93+
rc, out, err = assert_python_ok('-m', 'json.tool', infile)
94+
95+
self.assertEqual(rc, 0)
96+
self.assertEqual(out.splitlines(), expect.splitlines())
97+
self.assertEqual(err, b'')
98+
8499
def test_infile_outfile(self):
85100
infile = self._create_infile()
86101
outfile = support.TESTFN + '.out'
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix ``json.tool`` failed to read a JSON file with non-ASCII characters when
2+
locale encoding is not UTF-8.

0 commit comments

Comments
 (0)