Skip to content

Commit ea7e2c4

Browse files
authored
Merge pull request #92 from xingzhao-ji/fix-cli-malformed-json-batches
Continue CLI batches after malformed JSON input
2 parents 86b82bf + 15079d6 commit ea7e2c4

3 files changed

Lines changed: 112 additions & 5 deletions

File tree

‎bin/jsonpointer‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ parser.add_argument('FILE', type=str, nargs='+',
2727
help='Files for which the pointer should be resolved')
2828
parser.add_argument('--indent', type=int, default=None,
2929
help='Indent output by n spaces')
30+
parser.add_argument('--continue-on-error', action='store_true',
31+
help='Continue with remaining files after JSON or text decoding errors')
3032
parser.add_argument('-v', '--version', action='version',
3133
version='%(prog)s ' + jsonpointer.__version__)
3234

@@ -77,8 +79,8 @@ def parse_pointer(args):
7779
def resolve_files():
7880
""" Resolve a JSON pointer on JSON files
7981
80-
Returns False if the pointer could not be resolved on at least one
81-
file. """
82+
Returns False if the pointer could not be resolved on at least one file,
83+
or if --continue-on-error skipped a JSON or text decoding error. """
8284
args = parser.parse_args()
8385

8486
ptr, files = parse_pointer(args)
@@ -90,7 +92,16 @@ def resolve_files():
9092
except argparse.ArgumentTypeError as e:
9193
parser.error(str(e))
9294

93-
doc = json.load(f)
95+
try:
96+
doc = json.load(f)
97+
except (json.JSONDecodeError, UnicodeDecodeError) as e:
98+
if not args.continue_on_error:
99+
raise
100+
print('Could not parse JSON in %r: %s' % (name, e),
101+
file=sys.stderr)
102+
ok = False
103+
continue
104+
94105
try:
95106
result = jsonpointer.resolve_pointer(doc, ptr)
96107
print(json.dumps(result, indent=args.indent))

‎doc/commandline.rst‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ that can be used to resolve a JSON pointers on JSON files.
66

77
The program has the following usage ::
88

9-
usage: jsonpointer [-h] [-f POINTER_FILE | -p POINTER] [--indent INDENT] [-v]
9+
usage: jsonpointer [-h] [-f POINTER_FILE | -p POINTER] [--indent INDENT]
10+
[--continue-on-error] [-v]
1011
[POINTER] FILE [FILE ...]
1112

1213
Resolve a JSON pointer on JSON files
@@ -23,6 +24,8 @@ The program has the following usage ::
2324
-p POINTER, --pointer POINTER
2425
A JSON pointer expression
2526
--indent INDENT Indent output by n spaces
27+
--continue-on-error Continue with remaining files after JSON or text
28+
decoding errors
2629
-v, --version show program's version number and exit
2730

2831
The pointer can be passed as the first positional argument, with ``-p``, or
@@ -33,6 +36,13 @@ could not be resolved on at least one file (the remaining files are still
3336
processed) and 2 on usage errors, such as an invalid pointer or a missing
3437
file.
3538

39+
By default, invalid JSON or a text decoding error stops processing. With
40+
``--continue-on-error``, these errors are reported on standard error with
41+
the file name and decoder details, and the remaining files are processed.
42+
The exit status is 1 if any file has such an error, even if later files
43+
succeed. Missing files and other usage errors still stop processing with
44+
status 2.
45+
3646
Example
3747
^^^^^^^
3848

‎tests.py‎

Lines changed: 87 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -507,7 +507,7 @@ def _write(self, name, content):
507507
f.write(content)
508508

509509
def _run(self, *args):
510-
env = dict(os.environ, PYTHONPATH=self.ROOT)
510+
env = dict(os.environ, PYTHONPATH=self.ROOT, PYTHONUTF8='1')
511511
return subprocess.run([sys.executable, self.SCRIPT] + list(args),
512512
cwd=self.dir, env=env, capture_output=True,
513513
text=True)
@@ -584,6 +584,92 @@ def test_unresolvable_pointer_in_one_file(self):
584584
self.assertIn('Could not resolve pointer', proc.stderr)
585585
self.assertEqual(proc.stdout, '1\n')
586586

587+
def test_invalid_json(self):
588+
for content in ('', '{"a": }', '{"a": 1}\n{"a": 2}'):
589+
with self.subTest(content=content):
590+
self._write('invalid.json', content)
591+
proc = self._run('--continue-on-error', '/a', 'invalid.json')
592+
self.assertEqual(proc.returncode, 1)
593+
self.assertEqual(proc.stdout, '')
594+
self.assertIn("Could not parse JSON in 'invalid.json':",
595+
proc.stderr)
596+
self.assertIn('line ', proc.stderr)
597+
self.assertNotIn('Traceback', proc.stderr)
598+
599+
def test_invalid_json_in_one_file(self):
600+
self._write('invalid.json', '{"a": }')
601+
for index in range(3):
602+
with self.subTest(index=index):
603+
files = ['a.json', 'b.json']
604+
files.insert(index, 'invalid.json')
605+
proc = self._run('--continue-on-error', '/a', *files)
606+
self.assertEqual(proc.returncode, 1)
607+
self.assertEqual(proc.stdout, self.A_OUT + self.B_OUT)
608+
self.assertIn("Could not parse JSON in 'invalid.json':",
609+
proc.stderr)
610+
self.assertNotIn('Traceback', proc.stderr)
611+
612+
def test_invalid_json_and_unresolvable_pointer(self):
613+
self._write('invalid.json', '{"a": }')
614+
proc = self._run('--continue-on-error', '/b',
615+
'invalid.json', 'a.json', 'b.json')
616+
self.assertEqual(proc.returncode, 1)
617+
self.assertEqual(proc.stdout, '1\n')
618+
self.assertIn("Could not parse JSON in 'invalid.json':", proc.stderr)
619+
self.assertIn('Could not resolve pointer:', proc.stderr)
620+
self.assertNotIn('Traceback', proc.stderr)
621+
622+
def test_invalid_json_stops_without_continue_on_error(self):
623+
self._write('invalid.json', '{"a": }')
624+
for index in range(3):
625+
with self.subTest(index=index):
626+
files = ['a.json', 'b.json']
627+
files.insert(index, 'invalid.json')
628+
proc = self._run('/a', *files)
629+
self.assertEqual(proc.returncode, 1)
630+
self.assertEqual(proc.stdout,
631+
''.join([self.A_OUT, self.B_OUT][:index]))
632+
self.assertIn('JSONDecodeError', proc.stderr)
633+
634+
def test_invalid_encoding_in_one_file(self):
635+
with open(os.path.join(self.dir, 'invalid.json'), 'wb') as f:
636+
f.write(b'{"a":"\xff"}')
637+
for index in range(3):
638+
with self.subTest(index=index):
639+
files = ['a.json', 'b.json']
640+
files.insert(index, 'invalid.json')
641+
proc = self._run('--continue-on-error', '/a', *files)
642+
self.assertEqual(proc.returncode, 1)
643+
self.assertEqual(proc.stdout, self.A_OUT + self.B_OUT)
644+
self.assertIn("Could not parse JSON in 'invalid.json':",
645+
proc.stderr)
646+
self.assertIn('decode', proc.stderr)
647+
self.assertNotIn('Traceback', proc.stderr)
648+
649+
def test_invalid_encoding_stops_without_continue_on_error(self):
650+
with open(os.path.join(self.dir, 'invalid.json'), 'wb') as f:
651+
f.write(b'{"a":"\xff"}')
652+
proc = self._run('/a', 'a.json', 'invalid.json', 'b.json')
653+
self.assertEqual(proc.returncode, 1)
654+
self.assertEqual(proc.stdout, self.A_OUT)
655+
self.assertIn('UnicodeDecodeError', proc.stderr)
656+
657+
def test_continue_on_error_with_valid_files(self):
658+
for pointer in (['/a'], ['-p', '/a'], ['-f', 'ptr.txt']):
659+
with self.subTest(pointer=pointer):
660+
proc = self._run('--continue-on-error', *pointer,
661+
'a.json', 'b.json')
662+
self.assertEqual(proc.returncode, 0, proc.stderr)
663+
self.assertEqual(proc.stdout, self.A_OUT + self.B_OUT)
664+
self.assertEqual(proc.stderr, '')
665+
666+
def test_continue_on_error_does_not_skip_missing_files(self):
667+
proc = self._run('--continue-on-error', '/a',
668+
'a.json', 'missing.json', 'b.json')
669+
self.assertEqual(proc.returncode, 2)
670+
self.assertEqual(proc.stdout, self.A_OUT)
671+
self.assertIn('missing.json', proc.stderr)
672+
587673
def test_pointer_file_requires_value(self):
588674
proc = self._run('-f', '-p', '/a', 'a.json')
589675
self.assertEqual(proc.returncode, 2)

0 commit comments

Comments
 (0)