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 list | None. 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 — absent | KeyError, 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) throughJSON.parseand it comes back as9007199254740992— 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.
1e999is grammatically fine JSON, but it parses toInfinityin JavaScript andinfin Python. A value that looks finite in the logs is non-finite in memory. Assertisfinite()on ingest. - NaN smuggling. NaN and Infinity are not valid JSON — but Python's
json.dumpswill emit them (NaN,Infinity) unless you passallow_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 byJSON.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.parsethrows 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
| Payload | Exercises | Assert |
|---|---|---|
{"items": null} | Tri-state handling | 400 or documented null semantics — not a 500 |
{} | Absent optional keys | Defaults applied; no KeyError anywhere |
ID of 9007199254740993 | Double precision | Survives the round-trip or is rejected — never silently rewritten |
1e999 | Non-finite guard | Rejected or flagged on ingest |
"\ud800" | Encoding round-trip | Rejected before it reaches storage |
| Emoji + combining diacritics in a name | Grapheme vs code-unit counting | Length checks behave consistently |
{"a": 1, "a": 2} | Duplicate keys | Rejected, or last-wins documented |
| 500 levels of nesting | Recursion limits | Depth cap trips cleanly; no stack overflow |
Top-level scalar 42 | Non-object roots | Accepted 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.
Related Posts
How to Test File Upload Features: A Developer's Guide
Learn the best practices for testing file upload functionality in web applications using sample files.
Read moreTestingSample PDF Files for Testing: Complete Guide
Everything you need to know about using sample PDF files for development and testing.
Read moreFile FormatsTest JSON Files: How to Validate Your API Pipeline
Learn how to use sample JSON files to test API endpoints, parsers, and data processing pipelines.
Read more