Product case study · November 16, 2026

Ask Claude Code to catch JSON keys before they disappear

Build a small Python loader with Claude Code that rejects duplicate JSON keys, including nested and escaped names, before values disappear.

Reading time
6 min
Checked
Nov 16, 2026
Two paper cards with matching blue tabs stopped by an ochre inspection bar before entering a filing tray
Catch the repeated field before the parser chooses a winner.
Bottom line

Check duplicate keys while parsing the original text. Once they become a dictionary, the evidence is gone.

A settings file can say “preview” and “publish” for the same field. Python’s default JSON loader keeps the second value, and the first disappears. By the time an agent checks the resulting dictionary, there is nothing left to flag.

This makes a satisfying small repair for Claude Code: move the check to the moment the parser still has both entries. The interesting part is deciding what counts as a duplicate. Two fields in one object should fail; the same field in two separate objects should work.

The examples below are fictional practice data. You need 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 Claude prompts are an authored walkthrough, not a recorded agent run. Sources were checked November 16, 2026.

Watch one value vanish

Create a disposable folder and a loader that accepts whatever Python normally accepts:

json_lab=$(mktemp -d /tmp/claude-json-keys.XXXXXX)
cd "$json_lab"
cat > config_reader.py <<'PY'
import json


def load_config(text):
    return json.loads(text)
PY
python3 - <<'PY'
from config_reader import load_config
print(load_config('{"mode":"preview","mode":"publish"}'))
PY

The result is {'mode': 'publish'}. This is documented behavior in Python’s JSON reference, not an agent mistake. RFC 8259, section 4 recommends unique names within an object and describes differing receiver behavior when names repeat.

For a settings loader, I would reject the ambiguity. Guessing which value the author intended is a poor job for either a parser or an AI assistant.

Write the rule before asking for code:

cat > SPEC.md <<'SPEC'
load_config(text) accepts a JSON string and returns its decoded value.
Reject repeated decoded field names within any single object with ValueError.
This includes nested objects and objects inside arrays.
Reject repeats even when the two values are equal.
Allow the same field name in different objects.
Preserve normal decoding for inputs without duplicate names.
Let malformed JSON raise ValueError (including its JSONDecodeError subclass).
Do not repair or rewrite the input. Use only Python's standard library.
This exercise adds duplicate-name rejection, not full schema validation.
SPEC

Give the agent the awkward cases

Save this as test_config_reader.py in that folder:

import unittest
from config_reader import load_config


class ConfigTests(unittest.TestCase):
    def test_rejects_duplicate_names(self):
        cases = [
            '{"mode":"preview","mode":"publish"}',
            '{"job":{"retries":1,"retries":2}}',
            '[{"enabled":true,"enabled":false}]',
            '{"limit":3,"limit":3}',
            r'{"mode":"preview","\u006dode":"publish"}',
        ]
        for text in cases:
            with self.subTest(text=text):
                with self.assertRaises(ValueError):
                    load_config(text)

    def test_allows_separate_objects(self):
        text = '{"first":{"mode":"preview"},"second":{"mode":"publish"}}'
        self.assertEqual(load_config(text), {
            "first": {"mode": "preview"},
            "second": {"mode": "publish"},
        })

    def test_preserves_normal_values(self):
        self.assertEqual(
            load_config('{"items":[1,true,null,"mode"],"empty":{}}'),
            {"items": [1, True, None, "mode"], "empty": {}},
        )

    def test_rejects_malformed_json(self):
        with self.assertRaises(ValueError):
            load_config('{"mode":}')

Run the baseline:

python3 -m unittest -v test_config_reader

There are eight input cases across four test methods. The original loader fails the five duplicate cases. The raw string in the fifth case matters: it leaves the Unicode escape in the JSON text so the parser, rather than Python’s string literal reader, decodes it. Both spellings then name the same field.

Start claude in this folder and paste:

Read SPEC.md, config_reader.py and test_config_reader.py.
Run python3 -m unittest -v test_config_reader to establish the baseline.
Explain where the repeated entries disappear during parsing.
Change only config_reader.py to satisfy SPEC.md.
Keep the tests and specification unchanged. Do not install packages.
Run the same tests again and report the actual result.
Explain why the fix catches nested and escaped duplicate names,
but permits matching field names in different objects.
Do not commit, delegate, or add unrelated features.

Anthropic’s common workflows supports this approach: provide a reproducible command, describe the bug, and verify the repair with tests. Review tool permissions for the practice folder; a prompt is not a filesystem sandbox.

Review where the check happens

A small reference implementation is:

import json


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"duplicate JSON key: {key!r}")
        result[key] = value
    return result


def load_config(text):
    return json.loads(text, object_pairs_hook=unique_object)

Python documents object_pairs_hook as receiving an ordered list of pairs for each decoded object. That gives the function a chance to reject a repeat before building its dictionary. Each invocation has a fresh result, so unrelated objects do not share a global list of forbidden names. The parser has already decoded escaped names when the hook receives them. See the JSON decoder reference.

A repair that calls ordinary json.loads first and then walks its dictionaries is too late. A regular expression is also the wrong tool here: nesting, escaped names and strings containing punctuation belong to the parser.

Exit Claude, inspect config_reader.py, and rerun the test command yourself. In the local reference check, the repaired loader passed all four methods and all eight input cases. That verifies this implementation against this contract; it does not establish how a particular Claude session will behave.

Stop at the boundary you actually built

If an import fails, check that both Python files are in the current practice folder. If the duplicate cases still pass silently, check that load_config actually supplies object_pairs_hook. If separate objects fail, look for a shared set of keys outside the hook.

The error identifies the repeated name, but it does not report a complete nested path or line number. That is enough for this small exercise. A production editor might need richer diagnostics.

This loader also does not enforce required settings, permitted values, or a top-level object. It preserves Python’s other decoding behavior, including its default handling of nonstandard numeric constants. Define those requirements separately before calling a loader “strict.”

Use the duplicate check on the original JSON text. If another system has already parsed and reserialized it, the discarded entry cannot be recovered by this function. That is the useful lesson to carry into your next agent task: ask where information is lost, then put the check just before that point.

Sources

Checked November 16, 2026:

Put this to work

Why duplicate detection belongs at the parsing boundary.

Try

Build and repair a tiny JSON loader in a disposable Python practice folder.

Prove it worked

Run eight fixed cases against the original and repaired loaders.

Keep in view

  • Reproduce Python's last-value-wins behavior with a fictional settings file.
  • Ask Claude Code for a repair that catches nested and escaped duplicate names.
  • Keep identical field names legal when they belong to different objects.
Learn the workflow: Start a Claude Code project session