Product case study · November 20, 2026

Ask Claude Code to catch infinity hiding in JSON

Repair a Python JSON loader with Claude Code: reject NaN, Infinity and overflowing exponents while preserving ordinary numbers and quoted text.

Reading time
6 min
Checked
Nov 20, 2026
A paper sieve catches jagged charcoal stones while smooth blue circles pass into an evidence tray on warm paper.
Check both the token you receive and the number it becomes.
Bottom line

Rejecting NaN is only half the repair. Test a large exponent too, because valid numeric syntax can still become infinity.

A JSON import can succeed and still hand your application infinity. The sneaky case is 1e400: it looks like an ordinary number, yet Python’s default decoder turns it into a floating-point infinity.

That’s a good small job for Claude Code because the obvious repair is incomplete. Ask it to reject NaN, then give it a large exponent. The second test forces a more useful conversation about what your application actually accepts.

This lab uses fictional data, Bash on macOS, Linux or WSL, Python 3, and an installed, signed-in Claude Code. The Python baseline and reference repair were checked locally. The agent prompt is an authored exercise, not a recorded Claude run. Official sources were checked November 20, 2026.

Reproduce both entrances

Create a disposable folder and a minimal loader:

finite_lab=$(mktemp -d /tmp/claude-finite-json.XXXXXX)
cd "$finite_lab"
cat > payload_reader.py <<'PY'
import json


def load_payload(text):
    return json.loads(text)
PY
python3 - <<'PY'
from payload_reader import load_payload
for text in ['{"score":NaN}', '{"score":1e400}']:
    print(load_payload(text))
PY

The baseline prints:

{'score': nan}
{'score': inf}

These cases have different causes. RFC 8259, section 6 excludes NaN and infinity literals from JSON’s number grammar. It also permits implementations to limit numeric range and precision. 1e400 follows the grammar; representing it as a finite Python float is the problem.

For this exercise, the policy is simple: decoded floating-point values must be finite. Don’t silently turn a missing measurement into zero or null. That would invent a meaning the sender never supplied.

Write the acceptance rule

Save this as SPEC.md:

load_payload(text) decodes a JSON string using Python's usual types.
Reject unquoted NaN, Infinity and -Infinity with ValueError anywhere.
Reject numeric tokens that convert to a non-finite float, including 1e400
and -1e400, at any nesting depth or at the document root.
Preserve ordinary finite floats, integers, booleans, null, arrays and objects.
Preserve quoted strings such as "NaN", "Infinity" and "1e400" unchanged.
Malformed JSON must still raise ValueError or its JSONDecodeError subclass.
Use only the standard library. Change only payload_reader.py.
Do not change this specification or the tests.
This is a finite-float policy, not full schema or precision validation.

Save these tests as test_payload_reader.py:

import unittest
from payload_reader import load_payload


class PayloadTests(unittest.TestCase):
    def test_rejects_special_constants(self):
        for token in ("NaN", "Infinity", "-Infinity"):
            for text in (token, '{"items":[' + token + ']}'):
                with self.subTest(text=text):
                    with self.assertRaises(ValueError):
                        load_payload(text)

    def test_rejects_overflow(self):
        for token in ("1e400", "-1e400"):
            for text in (token, '{"items":[' + token + ']}'):
                with self.subTest(text=text):
                    with self.assertRaises(ValueError):
                        load_payload(text)

    def test_preserves_normal_values(self):
        self.assertEqual(
            load_payload('{"items":[1,1.25,1e2,true,false,null]}'),
            {"items": [1, 1.25, 100.0, True, False, None]},
        )
        self.assertIsInstance(load_payload("1.25"), float)
        self.assertIsInstance(load_payload("123"), int)
        self.assertEqual(load_payload(str(10**400)), 10**400)

    def test_preserves_strings(self):
        self.assertEqual(
            load_payload('["NaN","Infinity","-Infinity","1e400"]'),
            ["NaN", "Infinity", "-Infinity", "1e400"],
        )

    def test_rejects_malformed_json(self):
        with self.assertRaises(ValueError):
            load_payload('{"score":}')

Run:

python3 -m unittest -v test_payload_reader

The baseline runs five methods and reports ten failing subtests: six for special constants and four for exponent overflow. Ordinary values, strings and malformed-input handling already meet the contract. The large integer check matters too: a number can exceed float range while remaining a perfectly usable Python integer.

Give Claude the failure, not a guessed patch

Start claude inside this folder and paste:

Read SPEC.md, payload_reader.py and test_payload_reader.py.
Run python3 -m unittest -v test_payload_reader to record the baseline.
Explain the difference between the special-constant and overflow failures.
Change only payload_reader.py to satisfy the specification.
Keep tests and SPEC.md unchanged. Do not install packages, commit or delegate.
Run the same tests again and report the actual output.
Explain how the fix handles nested numbers without rewriting quoted strings,
and why the 401-digit integer should still work.

This follows Anthropic’s debugging workflow: supply reproduction steps and verify the fix. Review the session’s permissions and proposed commands; a requested file boundary is not a filesystem sandbox.

I would keep these tests fixed during the repair. If the agent removes the overflow cases to get a green run, it has changed the job rather than finished it.

Review the two checks

A reference implementation is:

import json
import math


def reject_constant(token):
    raise ValueError(f"non-finite JSON constant: {token}")


def finite_float(token):
    value = float(token)
    if not math.isfinite(value):
        raise ValueError(f"JSON number exceeds finite float range: {token}")
    return value


def load_payload(text):
    return json.loads(
        text,
        parse_constant=reject_constant,
        parse_float=finite_float,
    )

Python’s decoder documentation describes separate hooks for special constants and floating-point tokens. They apply during parsing, including inside nested containers. Quoted strings never enter these hooks. Integers retain the decoder’s ordinary integer path.

math.isfinite checks the converted float. That catches the overflow which a constant-only hook misses. The reference repair passed all five test methods locally, including the ten rejection subtests.

Two tempting options don’t solve this job. allow_nan=False belongs to JSON encoding, so it isn’t a switch for loads. The decoder’s strict=True option controls unescaped control characters in strings; it doesn’t enforce this numeric policy. Python documents those distinctions in its JSON reference.

Exit Claude and run the test command yourself. If only the special-constant tests pass, inspect whether parse_float is connected. If strings fail, look for text replacement or a scan that ignores JSON syntax. If the large integer fails, look for code that converts every number to a float. If imports fail, run from the folder containing both Python files.

Know what a passing run buys you

This loader rejects non-finite results; it does not promise exact decimal arithmetic. Tiny values can underflow to zero, and ordinary floats can round. If your application requires exact decimals, define that contract separately rather than quietly returning a different numeric type from this function.

Required fields, permitted ranges, duplicate keys and input-size limits are also separate decisions. The duplicate-key tutorial handles a different parsing problem, while atomic JSON saves protects an output file during writing.

Keep 1e400 in the regression suite. It’s the case that distinguishes “we banned three words” from “we checked the number the application will receive.”

Sources

Checked November 20, 2026:

Put this to work

Why rejecting special constants does not catch floating-point overflow.

Try

Repair one loader in a disposable Python practice folder.

Prove it worked

Run the same five test methods against the baseline and reference repair.

Keep in view

  • Reproduce two ways non-finite numbers enter a Python JSON loader.
  • Give Claude Code fixed tests for constants, overflowing exponents and normal values.
  • Keep quoted numeric-looking text unchanged.
Learn the workflow: Set up your first Claude Code project session