From 1e71410060b3933cc7b99f8c059811cc5171fc6c Mon Sep 17 00:00:00 2001 From: rahul05ranjan <11793455+rahul05ranjan@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:11:03 +0000 Subject: [PATCH] fix: print a clean parse error in the CLI instead of a traceback Malformed input to python -m json5 escaped as a raw ValueError traceback, while the dump half of main() already handled its ValueErrors by printing str(error) to stderr and returning 1. Wrap the loads() call the same way so parse errors print a clean message and exit non-zero, like stdlib json.tool. Fixes #162 Co-authored-by: rahul05ranjan <11793455+rahul05ranjan@users.noreply.github.com> --- json5/tool.py | 7 ++++++- tests/tool_test.py | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/json5/tool.py b/json5/tool.py index c5fb34c..05b27b2 100644 --- a/json5/tool.py +++ b/json5/tool.py @@ -65,7 +65,12 @@ def main(argv=None, host=None): args.trailing_commas = False args.quote_style = json5.QuoteStyle.ALWAYS_DOUBLE.value - obj = json5.loads(inp, strict=args.strict) + try: + obj = json5.loads(inp, strict=args.strict) + except ValueError as error: + host.print(str(error), file=host.stderr) + return 1 + try: s = json5.dumps( obj, diff --git a/tests/tool_test.py b/tests/tool_test.py index a200b27..81934f6 100644 --- a/tests/tool_test.py +++ b/tests/tool_test.py @@ -158,6 +158,30 @@ def test_as_json_nonfinite(self): ) self.check(['-c', 'NaN'], out='NaN\n') + def test_invalid_input(self): + # Parse errors should print a clean message like the dump errors + # do, not a traceback. + self.check( + ['-c', '{bad'], + returncode=1, + out='', + err=':1 Unexpected end of input at column 5\n', + ) + self.check( + [], + stdin='{oops', + returncode=1, + out='', + err=':1 Unexpected end of input at column 6\n', + ) + self.check( + [], + stdin='', + returncode=1, + out='', + err='Empty strings are not legal JSON5\n', + ) + def test_quote_keys(self): self.check( ['--quote-keys', '-c', '{foo: 1}'],