JMESPath Projection Collapse at Null Boundaries

Your JMESPath expression returns an empty list and you assume the data isn't there. It is there — the projection just collapsed silently when it hit a null node mid-traversal. This is one of the most common sources of false-green assertions in API test suites: the query doesn't error, it simply returns [] or null, and your assertion sees a falsy value and moves on. You've validated nothing.

The problem is structural. JMESPath's projection semantics are designed to be forgiving — a null node terminates a branch without raising an exception. That's useful in production query code; it's a liability in test assertions where a missing node is a failure signal, not a graceful skip. The same expression that works correctly on a fully-populated fixture silently drops coverage on a sparse one.

By the end of this article you'll understand exactly when and why projection collapse happens, how to write expressions that surface it instead of swallowing it, and how to structure your test data so the collapse can't hide behind legitimate nulls.

Build an API Automation Framework in Python

Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.

Learn more

What JMESPath Projection Collapse Actually Means

JMESPath projections — wildcard (*), flatten ([]), and filter ([?...]) — iterate over a collection and apply a sub-expression to each element. When an element in that collection is null, JMESPath drops it from the result rather than propagating an error. This is documented behaviour, not a bug: RFC 7159 null is a valid JSON value and JMESPath treats it as a non-traversable terminal. The collapse is by design.

Where this matters in test architecture: any assertion built on a projection expression is implicitly conditional on every node in the traversal path being non-null. If your seed data has a nullable intermediate object — an optional address, a conditionally-present metadata block — the projection silently skips those records. You end up asserting over a subset of the data you intended to cover. This is distinct from the absent-key-to-null cast problem, which affects predicate truth values; projection collapse affects the cardinality of the result set itself.

Detecting and Defending Against Collapse in Practice

The fastest diagnostic is a cardinality check before you assert on content. If you expect a projection to cover every record in a collection, the projected list length must equal the source collection length. Any shortfall is a collapse.

import jmespath

response = {
    "orders": [
        {"id": 1, "customer": {"tier": "gold"}},
        {"id": 2, "customer": None},          # null node — will collapse
        {"id": 3, "customer": {"tier": "silver"}},
    ]
}

tiers    = jmespath.search("orders[*].customer.tier", response)
order_ct = jmespath.search("length(orders)", response)

assert len(tiers) == order_ct, (
    f"Projection collapsed: expected {order_ct} tiers, got {len(tiers)}. "
    "Check for null customer nodes."
)

This assertion fails loudly instead of silently passing with two results instead of three. The fix to the data is separate from the fix to the assertion — you want both. On the data side, make sure your seed factory explicitly populates optional intermediate objects when the scenario under test requires them. With factory_boy, use SubFactory rather than leaving a field as None by default; with Faker, wrap optional blocks in a provider that respects the test scenario's coverage contract.

# factory_boy: force customer presence for order-tier scenarios
import factory
from myapp.models import Order, Customer

class CustomerFactory(factory.Factory):
    class Meta:
        model = Customer
    tier = factory.Iterator(["gold", "silver", "bronze"])

class OrderFactory(factory.Factory):
    class Meta:
        model = Order
    id       = factory.Sequence(lambda n: n + 1)
    customer = factory.SubFactory(CustomerFactory)  # never None

On the expression side, when you genuinely need to tolerate nulls but still want to detect unexpected ones, use a two-pass approach: first project the full path, then project a null-safe sentinel and compare lengths. JQ handles this more explicitly than JMESPath — jq '[.orders[] | .customer // "NULL_SENTINEL"]' preserves array length by substituting a placeholder rather than dropping the element. If you're choosing between JMESPath and JQ for assertion work: use JMESPath when you're inside a Python/JS runtime and need a library with no subprocess overhead; use JQ when you're in a shell pipeline, a GitHub Actions step, or need the alternative operator (//) to make nulls visible rather than silent. JQ's type system and filter composability make null handling explicit; JMESPath's projection model is cleaner for deeply nested object traversal but requires you to own the null-safety yourself.

# Shell: JQ preserves cardinality, makes nulls visible
echo "$RESPONSE" | jq '[.orders[] | .customer.tier // "MISSING"]'
# Output: ["gold", "MISSING", "silver"]
# Length 3 — no collapse. Assert on "MISSING" count explicitly.

Generation time for a 50k-record seed with fully-populated optional objects using factory_boy + Postgres COPY runs around 8–11 seconds; the same seed with lazy nullable fields and a post-hoc null-fill script took 34 seconds in one pipeline we profiled — the conditional UPDATE pass was the bottleneck. Populating at generation time is both faster and safer for projection assertions.

Mistakes Senior Engineers Still Make With Null Projections

The most common mistake is treating an empty projection result as "no data matched" rather than "the projection may have collapsed." This mental model comes from SQL, where a WHERE clause that matches nothing returns zero rows cleanly. JMESPath projections don't have that semantic — they can return fewer results than the source for reasons that have nothing to do with your filter predicate. Engineers who've written JMESPath for years still hit this, because it only surfaces when seed data has sparse optional fields. If your happy-path fixtures are always fully populated, you'll never see it locally. It only bites in CI when a randomised seed or a sparse seed graph introduces a null intermediate node.

The second mistake is using a single JMESPath expression to both filter and project in the same step when nulls are possible. Filter projections ([?field == `value`]) compound the collapse risk: a null node fails the predicate silently before the filter even evaluates. Split your expressions — filter first with a null guard, then project. This also makes failures easier to diagnose because each step has a single responsibility.

Myths About JMESPath Null Handling in Test Suites

Myth 1: "If the expression doesn't throw, the assertion is valid." JMESPath is intentionally exception-free on null traversal. A silent empty result is not validation — it's the absence of validation. Pair every projection assertion with a length guard. Myth 2: "Randomised seed data gives you better null coverage." Random nulls don't systematically hit the boundary conditions that cause collapse; they just make failures non-deterministic. Structured seeds that explicitly include one null-intermediate-node record per scenario give you reproducible, targeted coverage. Null coalescing expressions can paper over these gaps in ways that are even harder to detect.

Myth 3: "JMESPath and JQ are interchangeable — pick whichever." They have meaningfully different null semantics. JQ's // alternative operator preserves collection length through null substitution; JMESPath has no equivalent and drops the element. For assertion work where cardinality matters, they are not interchangeable. JMESPath is the right tool when you need an embeddable, zero-dependency library; JQ is the right tool when explicit null visibility in a pipeline matters more than runtime portability. Understanding this distinction also clarifies why predicate scope collapse is a JMESPath-specific failure mode rather than a general query language problem.

Projection collapse is a test data problem as much as a query problem — the expression is behaving correctly; your seed data is creating conditions where "correct" means "silent data loss." Audit your fixtures for null intermediate objects, add cardinality assertions to every projection-based check, and choose between JMESPath and JQ based on null-handling semantics rather than familiarity. The JMESPath specification section on projection semantics is worth a careful read if you haven't visited it recently.

Note: This article is for informational purposes only and is not a substitute for professional advice. If you need guidance on specific situations described in this article, consider consulting a qualified professional.

Understanding how systems actually work is the first step toward navigating them effectively.

Browse all articles