Skip to content
Back to Blog
2026-11-02Testing

JSON Edge Cases for API Testing: Nulls, Big Numbers, Unicode, and Other Traps

Your API tests probably post well-formed JSON: every field present, every string ASCII, every ID comfortably small. Then production sends {"items": null} where you expected a list, an ID bigger than 2^53, and a display name with an emoji in it — and the incident channel finds out which code paths you never tested.

The basics — realistic documents at realistic sizes — are covered by testing with a sample JSON file. This post is the other half: payloads that are valid JSON, parse without complaint, and still break things downstream.

The Tri-State Trap: null vs Missing vs Empty

"List the items" has three wrong implementations, and they all start here:

Payload"How many items?"Typical failure
{"items": []}0 — an honest empty listNone. This is the payload you tested with.
{"items": null}Not zero — unknown.length on null throws in JS; len(None) raises TypeError in Python
{}Not zero — absentKeyError, or an undefined that silently spreads downstream

All three are valid JSON and all three show up in real payloads. Pick one behavior per field in your contract — many APIs normalize absent arrays to empty lists — and reject the other two with a 400 instead of guessing. "Be liberal in what you accept" is how nulls end up in the database.

Numbers Lie

JSON has exactly one number type, and most runtimes map it onto an IEEE 754 double. That buys you three distinct traps:

  • The 2^53 ceiling. Doubles hold integers exactly only up to 2^53 − 1. Send 9007199254740993 (2^53 + 1) through JSON.parse and it comes back as 9007199254740992 — no error, silently wrong. This is why large platforms serialize IDs as strings, and why Snowflake-style ID generators need string fields from day one. Add a >2^53 ID to your fixtures now, before your users do.
  • Finite literals, non-finite values. 1e999 is grammatically fine JSON, but it parses to Infinity in JavaScript and inf in Python. A value that looks finite in the logs is non-finite in memory. Assert isfinite() on ingest.
  • NaN smuggling. NaN and Infinity are not valid JSON — but Python's json.dumps will emit them (NaN, Infinity) unless you pass allow_nan=False. Turn that off before you ship invalid JSON to someone else's strict parser. JavaScript does the opposite: JSON.stringify(NaN) returns "null", silently rewriting your data.

Unicode: Where Parsers Disagree

RFC 8259 says JSON interchange is UTF-8, and all the disagreement lives at the edges:

  • Surrogate pairs. 😀 serializes as \ud83d\ude00 — two code units, one grapheme. Code that counts UTF-16 code units sees a name length of 2; code that counts graphemes sees 1. Pick a definition before writing the maxlength validator.
  • Lone surrogates. "\ud800" is accepted by JSON.parse — it happily builds a string containing an unpaired surrogate. That string cannot be encoded as UTF-8; the moment Python tries .encode("utf-8"), you get a UnicodeEncodeError. Valid to parse, impossible to store. If your pipeline touches a database or a message queue, test this one.
  • The BOM. RFC 8259 says senders MUST NOT add a byte order mark and parsers MAY ignore one. JSON.parse throws on a BOM. User-uploaded .json files are the classic source — strip a leading U+FEFF before parsing.
  • Control characters. "\u0000" in a description field is legal per the grammar and lethal downstream — PostgreSQL rejects NUL bytes in text values. Escape it, strip it, or reject the payload; just decide before the database does.

Duplicate Keys and Key Order

The spec says object names SHOULD be unique — not MUST. {"role": "user", "role": "admin"} is valid JSON, and last-wins in most parsers. If you diff or sign payloads, also remember that key order carries no meaning: two documents that differ only in key order are semantically identical. Never compare raw JSON bytes — parse, then compare — or canonicalize (RFC 8785) if you genuinely need to compare serialized forms.

Nesting Depth

Every recursive parser has a ceiling. CPython's json.loads recurses and hits the interpreter limit around 1000 frames; Jackson 2.15+ caps stream nesting depth at 1000 by default; a hand-rolled validator can blow the stack at a few hundred levels. Put a 500-deep object in the suite — deep enough to catch naive recursion, shallow enough to pass real parsers.

Streaming Payloads: NDJSON

Bulk endpoints, logs, and event pipes speak newline-delimited JSON — one document per line — and the rules change:

  • One malformed line must not kill the batch: skip it, log the line number, keep going
  • The final line may or may not end with \n — both are normal
  • Lines can be huge, so cap what you buffer per line

Realistic line-delimited fixtures are easy to come by: grab one from the NDJSON sample page and corrupt a single line at a time.

A Copy-Paste Test Matrix

PayloadExercisesAssert
{"items": null}Tri-state handling400 or documented null semantics — not a 500
{}Absent optional keysDefaults applied; no KeyError anywhere
ID of 9007199254740993Double precisionSurvives the round-trip or is rejected — never silently rewritten
1e999Non-finite guardRejected or flagged on ingest
"\ud800"Encoding round-tripRejected before it reaches storage
Emoji + combining diacritics in a nameGrapheme vs code-unit countingLength checks behave consistently
{"a": 1, "a": 2}Duplicate keysRejected, or last-wins documented
500 levels of nestingRecursion limitsDepth cap trips cleanly; no stack overflow
Top-level scalar 42Non-object rootsAccepted or rejected per contract — on purpose

That last row is its own lesson: RFC 8259 allows any value as a complete JSON document, so 42, true, and null are all valid request bodies. If your handler assumes the root is an object, that's an assumption — test it.

Keep the Payloads as Files

Inline strings drift; files under version control don't. Keep one fixture per row of that matrix, feed them with curl --data @payload.json, and review diffs like code. Start from the sample JSON download, break a copy, commit both. And when the legacy endpoint you're stuck maintaining only speaks XML, sample XML files do the same job.

#json#api-testing#edge-cases#sample-data#validation