Skip to content

Commit 2b3827d

Browse files
methaneJake Taylor
authored andcommitted
bpo-33684: json.tool: Use utf-8 for infile and outfile. (pythonGH-17460)
1 parent 1b804d9 commit 2b3827d

File tree

3 files changed

+24
-5
lines changed

3 files changed

+24
-5
lines changed

Lib/json/tool.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,12 @@ 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='?',
24+
type=argparse.FileType(encoding="utf-8"),
2425
help='a JSON file to be validated or pretty-printed',
2526
default=sys.stdin)
26-
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
27+
parser.add_argument('outfile', nargs='?',
28+
type=argparse.FileType('w', encoding="utf-8"),
2729
help='write the output of infile to outfile',
2830
default=sys.stdout)
2931
parser.add_argument('--sort-keys', action='store_true', default=False,

Lib/test/test_json/test_tool.py

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

92-
def _create_infile(self):
92+
def _create_infile(self, data=None):
9393
infile = support.TESTFN
94-
with open(infile, "w") as fp:
94+
with open(infile, "w", encoding="utf-8") as fp:
9595
self.addCleanup(os.remove, infile)
96-
fp.write(self.data)
96+
fp.write(data or self.data)
9797
return infile
9898

9999
def test_infile_stdout(self):
@@ -103,6 +103,21 @@ def test_infile_stdout(self):
103103
self.assertEqual(out.splitlines(), self.expect.encode().splitlines())
104104
self.assertEqual(err, b'')
105105

106+
def test_non_ascii_infile(self):
107+
data = '{"msg": "\u3053\u3093\u306b\u3061\u306f"}'
108+
expect = textwrap.dedent('''\
109+
{
110+
"msg": "\\u3053\\u3093\\u306b\\u3061\\u306f"
111+
}
112+
''').encode()
113+
114+
infile = self._create_infile(data)
115+
rc, out, err = assert_python_ok('-m', 'json.tool', infile)
116+
117+
self.assertEqual(rc, 0)
118+
self.assertEqual(out.splitlines(), expect.splitlines())
119+
self.assertEqual(err, b'')
120+
106121
def test_infile_outfile(self):
107122
infile = self._create_infile()
108123
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)