Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions bin/jsonpointer
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ def open_input(name):
parser.error("can't open '%s': %s" % (name, e))


def read_input(stream):
"""Decode redirected stdin using the same encoding as named files."""
if stream is sys.stdin and not stream.isatty() and hasattr(stream, 'buffer'):
return stream.buffer.read().decode('utf-8')
return stream.read()


def parse_pointer(args):
""" Return the parsed pointer and the list of files to resolve it on

Expand All @@ -75,7 +82,7 @@ def parse_pointer(args):
# part of a member name.
pointer_file = open_input(args.pointer_file)
try:
ptr = pointer_file.read().rstrip("\r\n")
ptr = read_input(pointer_file).rstrip("\r\n")
except UnicodeDecodeError as e:
parser.error('could not decode pointer file: %s' % e)
finally:
Expand Down Expand Up @@ -112,7 +119,7 @@ def resolve_files():
f = open_input(name)

try:
doc = json.load(f)
doc = json.loads(read_input(f))
except (json.JSONDecodeError, UnicodeDecodeError) as e:
if not args.continue_on_error:
raise
Expand Down
2 changes: 2 additions & 0 deletions doc/commandline.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ The pointer can be passed as the first positional argument, with ``-p``, or
read from a file with ``-f``.

JSON input files and pointer files are read as UTF-8.
Use ``-`` to read a JSON document or a pointer from standard input.
Piped and redirected standard input is also read as UTF-8.

The exit status is 0 if the pointer could be resolved on all files, 1 if it
could not be resolved on at least one file (the remaining files are still
Expand Down
16 changes: 15 additions & 1 deletion tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -816,7 +816,7 @@ def test_keyboard_interrupt_exit_status(self):
cli = runpy.run_path(self.SCRIPT)
args = [self.SCRIPT, '/a', os.path.join(self.dir, 'a.json')]
with mock.patch.object(sys, 'argv', args), \
mock.patch('json.load', side_effect=KeyboardInterrupt):
mock.patch('json.loads', side_effect=KeyboardInterrupt):
with self.assertRaises(SystemExit) as caught:
cli['main']()
self.assertEqual(caught.exception.code, 130)
Expand All @@ -836,6 +836,20 @@ def test_utf8_pointer_file_without_utf8_mode(self):
self.assertEqual(json.loads(proc.stdout), 'expected')
self.assertEqual(proc.stderr, '')

def test_utf8_piped_input_with_legacy_stdio_encoding(self):
self._write('unicode.json', json.dumps({'ä': 'expected', 'ä': 'wrong'}))
env = dict(os.environ, PYTHONPATH=self.ROOT, PYTHONUTF8='0',
PYTHONIOENCODING='cp1252')
for args, stdin in ((['/ä', '-'], '{"ä": "expected"}'),
(['-f', '-', 'unicode.json'], '/ä\n')):
with self.subTest(args=args):
proc = subprocess.run([sys.executable, self.SCRIPT] + args,
cwd=self.dir, env=env, capture_output=True,
input=stdin.encode('utf-8'))
self.assertEqual(proc.returncode, 0, proc.stderr)
self.assertEqual(json.loads(proc.stdout), 'expected')
self.assertEqual(proc.stderr, b'')

def test_positional_pointer(self):
proc = self._run('/a', 'a.json', 'b.json')
self.assertEqual(proc.returncode, 0, proc.stderr)
Expand Down
Loading