JSON · 11 min read

How to Tell an Empty JSON Array From an Empty Object

Two characters of punctuation, zero visible content — yet the empty array and the empty object sit on opposite sides of the type system, and mixing them up quietly breaks integrations.

Abstract illustration of two different empty containers

Open a network response in a plain text editor and the two emptiest JSON values look exactly alike: [] and {}. Two punctuation characters, nothing between them, no syntax highlighting to help you. A reader skimming a log cannot tell them apart without stopping to think. Yet they are different JSON types — an ordered list versus an unordered map — and that difference drives how code iterates, how truthiness behaves in some languages, and what an API promises to return. Teams that treat the two as interchangeable ship integrations that parse cleanly and then misbehave.

This guide walks through the distinction from both sides: what breaks when a consumer receives the wrong shape, where each shape typically comes from in real APIs, how to identify the type in seconds, and how to make a deliberate, documented choice for your own endpoints.

Two types, one blank face

JSON defines an array as an ordered collection of values and an object as a collection of name/value pairs. Empty versions of each are legal and common:

// Both are valid JSON, both look "empty" at a glance
const asArray  = [];   // JSON type: array  — ordered list, zero elements
const asObject = {};   // JSON type: object — map of keys, zero entries

The similarity ends at the syntax. In JavaScript, typeof reports "object" for both — a historical quirk of the language — but Array.isArray() separates them reliably. Iteration differs immediately: an array supports for...of, .map(), .filter() and indexed access, while an object needs Object.keys(), Object.values() or Object.entries() before you can loop over anything. Calling .map() on an empty object throws a TypeError; calling Object.keys() on an array works but returns index strings, which is rarely what the author intended.

Truthiness adds a second trap. In JavaScript, an empty array is truthy, so if (items) passes even when there is nothing to render. In Python, an empty list and an empty dict are both falsy, so the same stylistic check silently inverts its meaning across languages. A developer moving from Python to JavaScript — or reviewing a colleague's code with the other language in mind — can easily "fix" a check into a bug.

The deepest difference is semantic. An empty array says: this is a list, and today it happens to contain nothing. An empty object says: this is a record, and today it happens to have no fields. Those are different claims about the data, and the rest of this guide is about what happens when the claim and the consumer disagree.

It is worth stating plainly that the two values are never equal, even though both are "empty." In JavaScript, [] === [] is false — objects compare by reference — and more importantly [] === {} is false because the types differ. Deep-equality helpers and test frameworks generally report an empty array and an empty object as different values, and JSON-based caching or deduplication logic that keys on a canonical string will treat "[]" and "{}" as distinct entries. If your test suite asserts expect(result).toEqual({}) against what the API actually returns as [], the assertion fails even though a human eyeballing the payload would call both "empty." The emptiness is identical; the type is not, and the tooling agrees with the type system, not with your eyes.

Where the confusion bites

A list that arrives as a map

The classic failure: a client is written against a contract that promises an array of items, and the server returns an object keyed by id instead — or returns an empty object where the client expected an empty array. Deserialization may not even fail. JavaScript's JSON.parse happily produces whatever structure the text describes; the error surfaces later, at the first method call:

// Client code written against the contract: { "results": [ ... ] }
const body = JSON.parse('{"results": {}}');

// Works only if results is an array:
const names = body.results.map(r => r.name);
// TypeError: body.results.map is not a function

Because the failure is a runtime exception far from the parse, debugging tends to start in the wrong place — the rendering layer, the state management, anything except the two characters that arrived over the wire.

Counting the wrong way

Two sibling mistakes follow from the type mix-up. Code that assumes an array checks .length; code that assumes an object checks Object.keys(...).length. Apply the wrong one and the result is either undefined (asking an object for .length) or a misleading number (asking Object.keys() to count an array — it returns index strings, so an array of ten items reports ten, by accident, while Object.keys([]) reports zero, which is correct only by coincidence).

// Assuming the wrong shape changes the question you are really asking
Object.keys([]).length;        // 0 — right answer, wrong tool
Object.keys({}).length;        // 0
[].length;                     // 0
({}).length;                   // undefined — objects have no length
Array.isArray([]);             // true — the reliable discriminator
Array.isArray({});             // false

The reliable rule in JavaScript: never infer the type from a property lookup. Call Array.isArray() first, then branch.

Python: dict versus list

The same confusion crosses language boundaries. A Python client that writes for item in payload["results"] iterates over values when the payload is a list, and over keys — id strings — when it is a dict. No exception is raised; the loop simply produces the wrong data, which then flows into models, databases, or reports:

import json

results = json.loads('{"results": {}}')["results"]   # a dict, not a list

for item in results:        # iterates over KEYS if results is a dict
    process(item)           # receives id strings, never full records

Guard with explicit type checks rather than truthiness, because in Python both empties are falsy and cannot be told apart by if not results:

if not isinstance(results, list):
    raise TypeError(f"expected a list, got {type(results).__name__}")

Rule of thumb: in any language, the first check after parsing should answer "is this the type the contract promised?" — Array.isArray() in JavaScript, isinstance(x, list) in Python — before any property access or iteration.

When validation does not save you

A common assumption is that schema validation makes this problem moot: the client validates the payload against a schema, and a wrong shape is rejected before it reaches business logic. That holds only if the schema actually specifies the type. A schema that merely says "results": {} without "type": "array" accepts both an array and an object, because {} in JSON Schema means "any valid JSON" — an empty schema, not an empty object. The same trap exists in OpenAPI documents where a list-typed field is declared as a bare object for convenience, and in languages with weakly-typed JSON handling: Go's encoding/json unmarshals into interface{} without complaint, C#'s JToken accepts anything, and dynamic objects in JavaScript reflect whatever arrived.

The practical consequence: type errors cross the network boundary invisibly unless the contract names the type explicitly. Validation is the enforcement mechanism, but the contract — the schema you actually write — is where the decision lives. If the type is not written down, no validator can enforce it.

Where each shape comes from

Empty containers are not random; each shape tends to signal something specific about how the producing side thinks. The table below summarizes the four most common "nothing here" serializations and how consumers usually read them:

SerializedFirst non-whitespace charJSON typeCommon interpretation
[][ArrayQuery ran, zero results; an empty batch to iterate
{}{ObjectEmpty record, empty cache entry, or a field that defaults to a map
nullnNullValue unknown, not applicable, or deliberately withheld
(field absent)——Not tracked by this endpoint version; do not rely on it

In practice, [] usually comes from collection endpoints: a search with no matches, a filter that excludes everything, a feed before the first post. {} usually comes from two places: resources serialized as maps — configuration blobs, caches, per-key aggregations — and, less happily, from default serialization behavior. Many frameworks emit {} for an uninitialized object field and null for an uninitialized scalar, so the shape you receive sometimes reflects the producer's implementation rather than an intentional contract.

The dangerous variant is a shape that changes with content: an endpoint returns {} when a search has no hits but [{...}, {...}] when it does. Consumers then write union-type handling for a contract that never documented the union. If you inherit an API like this, normalize at the boundary — convert empty objects to empty arrays in one adapter function — and note the quirk where your team can find it. If you own the API, fix the contract instead; the next section shows how.

Pagination introduces its own variants of the same question. A paginated list endpoint might return {"items": [...], "cursor": "..."}, where an empty final page is "items": [] with a null cursor. A less careful design omits items entirely on the last page, forcing clients to distinguish "field absent because the page is empty" from "field absent because the response is malformed." Versioned APIs drift here too: v1 of an endpoint may return a bare array while v2 wraps it in an object to make room for metadata — a legitimate evolution, but one that changes the meaning of the top-level shape and must be called out in the changelog, not discovered in a broken client.

Telling them apart in seconds

The fastest mechanical check works on raw text: look at the first non-whitespace character of the value. [ means array; { means object; n means null; " means string; a digit or - means number. This works even in logs and terminals, where syntax highlighting and tree views are unavailable:

// Distinguish by first non-whitespace character — works on raw text
const first = raw.trim()[0];
if (first === "[")      handleArray(JSON.parse(raw));
else if (first === "{") handleObject(JSON.parse(raw));
else                    handleScalar(JSON.parse(raw));

A tree view makes the same determination visually and instantly: array nodes render as numbered slots, object nodes render as key/value pairs, and the type is legible before you expand anything. When two payloads differ only in container shape, a side-by-side tree comparison shows the divergence at the root instead of hiding it among matching leaves.

Resist the temptation to infer type from behavior in production code — typeof x.map === "function" or truthiness checks. Those techniques produce code that works until a payload shape shifts, then fails obscurely. Explicit type predicates are one line, readable, and self-documenting.

Choosing a shape for your own API

When a list-valued field can be empty, the shape you return is a design decision, and the wrong default is expensive to change later. Three principles keep the choice deliberate.

Prefer [] for collections, always. An endpoint that lists things should return an empty array, not null and not an omitted field. Consumers can then write for (const item of results) with no guard, and the loop simply does nothing. This is one of the highest-leverage conventions in JSON API design: it removes an entire category of null checks from every client.

Reserve {} for maps. If the field is genuinely a keyed collection — per-tenant settings, cache entries, an aggregation bucketed by country — an empty object is correct and meaningful: "the map exists and has no entries." Returning {} for what is conceptually a list is the anti-pattern to avoid, because it forces every consumer to know that "empty object here actually means empty list."

Write the shape into the contract. Whether you publish OpenAPI, JSON Schema, or prose, state the type of every collection-valued field and its empty behavior: results: array of Item, may be empty; never null. A contract that specifies types makes shape drift a review failure instead of a production incident. The same discipline applies to error payloads — a consistent structure for failures is its own contract, covered in the guide on RFC 9457 problem details.

Plan for the day the shape must change. If an endpoint that once returned a bare array grows into a paginated envelope, the field inside it keeps its array type, but the top-level shape moves from [] to {} — and every consumer breaks simultaneously. Migrations like this are survivable when the contract versions the change, serves both shapes for a deprecation window, or documents a stable migration path. They are painful when the change ships as a side effect of a framework upgrade, because then the first signal is a production exception in someone else's codebase. Treat a change from array to object — or the reverse — as a breaking change with the same weight as removing a field, even though a diff of the empty cases shows nothing but two swapped punctuation marks.

Design note: picking [] versus {} for an empty field is not a style preference. It declares the field's type to every consumer, forever. Decide it once, document it, and never let the serialization layer choose for you.

Edge cases: null, missing, and whitespace

Empty is not the only "nothing." A field can be an empty array, an empty object, null, or absent entirely — four states that feel similar and behave differently:

{
  "a": [],       // array type, zero elements — iterate safely
  "b": {},       // object type, zero entries — read keys safely
  "c": null,     // value deliberately absent — guard required
  "d": "  "      // a string of whitespace — NOT empty, length 2
}

Three distinctions matter most. First, null is a value, not a container: it has no type-specific operations, so null.map and Object.keys(null) both throw. Second, an absent field and a null field are different facts — "not tracked" versus "tracked and empty" — and collapsing them loses information; the trade-offs are laid out in null vs empty vs missing. Third, whitespace is content: " " is a two-character string, not an empty value, and diffs that ignore trailing whitespace can hide real state changes between payloads.

Whitespace also matters for the first-character check: pretty-printed payloads indent their containers, so raw[0] may be a newline. Always trim before inspecting. And when navigating deeply nested documents — where an empty container and an escaped key can sit side by side — keep the escaping rules from JSON Pointer escapes in mind, since a key containing a slash or tilde changes how you address the very node you are trying to inspect.

A fourth subtlety appears in storage and message queues rather than HTTP: databases and brokers with columnar or typed bindings (PostgreSQL's jsonb, Kafka schema registries, ORM mappers) preserve the distinction between [], {} and null through the whole pipeline, while untyped text columns collapse it. A payload stored as [] and read back through an untyped driver may surface as a string, a null, or a parsed value depending on configuration. If empty containers are part of your state — "the batch ran and produced nothing" — verify that the round trip preserves the type, not just the apparent emptiness.

A short checklist

  • Identify the type before touching the value: Array.isArray() in JavaScript, isinstance() in Python — never truthiness.
  • Read the first non-whitespace character when working with raw text: [ is an array, { is an object.
  • Treat [] as the only correct empty for list-valued fields; reserve {} for keyed maps.
  • Distinguish null, absent, and empty in your schema — they are three different facts.
  • Write the type and empty behavior of every collection field into the API contract.
  • Normalize legacy endpoints that change shape with content at one adapter boundary.
  • Remember whitespace is content: " " is not empty, and indented payloads need trimming before a first-character check.

Test it yourself

Paste a payload with [] in one field and {} in another into the JSON Inspector — the tree view shows the type of each node instantly, numbered slots for arrays and key/value pairs for objects. Then run the same payload and a variant with the containers swapped through JSON Compare to see the difference flagged at the root. Both tools run entirely in your browser, so real API responses and log excerpts are safe to inspect.

Reproduce every example locally with the JSON Inspector or the matching tool on the workbench. Nothing you paste leaves your browser.