From 8cb8bc309ed3ff6c410c1f42af0a3d90c33f230b Mon Sep 17 00:00:00 2001 From: jwalith4418-Mj <232281058+jwalith4418-Mj@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:46:54 +0530 Subject: [PATCH] Reject non-finite numbers in JSON CLI output Pass allow_nan=False for --as-json and report encoding errors without emitting invalid JSON. Keep default JSON5 non-finite output supported. Prepared with AI assistance; contributor review is required before upload. --- json5/tool.py | 21 +++++++++++++-------- tests/tool_test.py | 9 +++++++++ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/json5/tool.py b/json5/tool.py index a778593..c5fb34c 100644 --- a/json5/tool.py +++ b/json5/tool.py @@ -66,13 +66,18 @@ def main(argv=None, host=None): args.quote_style = json5.QuoteStyle.ALWAYS_DOUBLE.value obj = json5.loads(inp, strict=args.strict) - s = json5.dumps( - obj, - indent=args.indent, - quote_keys=args.quote_keys, - trailing_commas=args.trailing_commas, - quote_style=QUOTE_STYLES[args.quote_style], - ) + try: + s = json5.dumps( + obj, + indent=args.indent, + quote_keys=args.quote_keys, + trailing_commas=args.trailing_commas, + quote_style=QUOTE_STYLES[args.quote_style], + allow_nan=not args.as_json, + ) + except ValueError as error: + host.print(str(error), file=host.stderr) + return 1 host.print(s) return 0 @@ -126,7 +131,7 @@ def _parse_args(host, argv): action='store_const', const=True, default=False, - help='output as JSON (same as --quote-keys --no-trailing-commas)', + help='output as JSON (reject non-finite numbers)', ) parser.add_argument( '--indent', diff --git a/tests/tool_test.py b/tests/tool_test.py index 730930a..a200b27 100644 --- a/tests/tool_test.py +++ b/tests/tool_test.py @@ -149,6 +149,15 @@ def test_as_json(self): out='"\\u0000\\u000b"\n', ) + def test_as_json_nonfinite(self): + self.check( + ['--as-json', '-c', '{value: NaN}'], + returncode=1, + out='', + err='Illegal JSON5 value: nan\n', + ) + self.check(['-c', 'NaN'], out='NaN\n') + def test_quote_keys(self): self.check( ['--quote-keys', '-c', '{foo: 1}'],