JSON Toolkit

JSON arrays and objects: structure and nesting for beginners

Bottom line: JSON gives you exactly two containers: objects for named fields, arrays for ordered lists. Learn how to combine them, when to pick which, and how to fix the three most common mistakes — fake arrays with numeric keys, trailing commas, and single quotes.

Beginner~6 min readPublished 2026-11-20Updated 2026-11-20
Cover introducing JSON array and object structure

JSON gives you exactly two containers: objects hold named fields, arrays hold ordered lists — and almost every malformed payload you will ever meet comes down to quotes, commas, or a list written as a fake object.

One: JSON has only two containers

No matter how complicated an API response looks, everything inside reduces to two containers and six value types. An object is a collection of key/value pairs wrapped in curly braces {}; an array is an ordered list of values wrapped in square brackets []. A value can be a string, a number, true, false, null — or another object or array. Objects inside arrays, arrays inside objects: that recursion is the entire expressive power of JSON.

{
  "user": { "name": "Ada", "active": true },
  "roles": ["admin", "editor"],
  "lastLogin": null,
  "loginCount": 42
}

This has a practical consequence: when a payload confuses you, do not read it character by character. First check whether the outermost character is { or [. If it is an object, read it as named fields; if it is an array, read it as a list, then descend level by level. The grammar diagram on json.org fits on a single page precisely because two structures plus recursion cover everything.

Two: writing objects, four hard rules

Objects are where beginners make the most mistakes, but the rules are only four:

  1. Keys must be double-quoted strings. {name: "Ada"} and {'name': 'Ada'} are both invalid; it has to be {"name": "Ada"}. JavaScript object literals allow bare keys and single quotes, JSON does not — this is the single most common confusion between the two.
  2. Separate pairs with commas, and never leave a comma after the last one. {"a": 1, "b": 2,} fails with Unexpected token } at the closing brace.
  3. Keys should be unique. RFC 8259 words this as SHOULD, not MUST: duplicate keys do not raise an error, but whether the parser keeps the first or the last value is implementation-defined, and languages disagree. Never rely on it.
  4. Key order carries no meaning. {"a":1,"b":2} and {"b":2,"a":1} are the same object; diff tools and comparison functions ignore key order. If order matters, the data belongs in an array.

Three: writing arrays, order is data

Arrays store values by position, and indexing starts at 0: in ["admin", "editor"], the string "editor" is [1]. That order is meaningful — this is the essential difference between arrays and objects. Search results ranked by relevance, log entries ordered by time: that information lives only in the sequence, and converting it to an object destroys it.

Two practical recommendations. First, keep array elements homogeneous: [{"id":1},{"id":2}] is far easier to consume than [1, "text", true], which is legal JSON but forces every consumer to branch on types at every step. Second, an empty array [] is a perfectly valid value — when a list field has no content yet, emit [] instead of null, so consumers do not have to check for existence first and emptiness second.

[
  { "city": "Tokyo", "population": 13960000 },
  { "city": "Delhi", "population": 16780000 }
]

Four: nesting, the four shapes of real payloads

Real data is just these two containers nested inside each other, and the patterns reduce to four shapes:

Shape Looks like Typical use
Object containing an array {"tags": ["a","b"]} List field of an entity
Array of objects [{"id":1},{"id":2}] Record lists, paginated results
Object containing an object {"db": {"host": "..."}} Grouped config, address blocks
Array of arrays [[1,2],[3,4]] Matrices, table rows

A typical API response uses an object as the shell and an array as the payload:

{
  "code": 0,
  "data": {
    "items": [
      { "id": 1, "title": "first" },
      { "id": 2, "title": "second" }
    ],
    "page": 1,
    "total": 2
  }
}

Do not nest for the sake of nesting. Beyond three or four levels, access paths become unreadable and consumer code inflates along with them. Fields that always travel together belong in a sub-object: replace addrCity and addrZip with address: {city, zip}.

Five: object or array, a decision table

Question Answer Why
Does every value have a name? Object Lookup by key; adding or removing fields breaks nothing
Is it a list of similar records? Array Order matters; you can map and filter
Do you need fast lookup by key? Object keyed by id O(1) access instead of scanning
Several attributes of one entity? Object Attributes have no inherent order
A growing collection of similar items? Array Length stretches freely

One anti-pattern deserves special mention: faking an array with an object whose keys are "0", "1", "2". It parses without errors, but you lose the length semantics and iteration tools of a real array, and consumers must sort Object.keys before reading anything. If the keys are sequential numbers, write a real array. The reverse also holds: a list of key/value pairs like [{"key":"theme","value":"dark"}] is inferior to the object {"theme": "dark"} — unless the keys are genuinely dynamic and cannot be declared in advance.

Six: three frequent mistakes and their error messages

Wrong form Typical error Fix
Trailing comma {"a":1,} Unexpected token } Delete the last comma
Single quotes / bare keys {name:'Ada'} Unexpected token ' / Expected property name Double quotes for keys and strings, always
Python literals True / None Unexpected token T Change to true / null
Fake array with numeric keys No error, wrong semantics Rewrite as a real array

Two debugging habits: parsers usually report a position after the offending character, so when you see position 42, look back one or two characters; and for a huge single-line JSON, pretty-print it first — line and column numbers beat character offsets every time. The full error catalogue lives in JSON error message lookup, and the step-by-step triage flow in how to fix JSON parse errors.

Seven: after writing, verify the structure

Hand-written JSON should always pass through a parser before delivery. The lightest verification is a command line:

python3 -m json.tool config.json > /dev/null && echo OK
jq empty config.json && echo OK

Online, paste the content into the JSON formatter and validator page — syntax errors come back with line and column positions. Switch to the tree view to see the type of every level at a glance: whether a number was parsed as a string, whether array lengths are what you expect. And when the audience is non-technical, an array-of-objects payload can be expanded into rows and columns on the JSON to table page, which doubles as a check that your data really is a tidy record list.

Questions about which field should be an array, or how to refactor nesting that has grown too deep, belong to type modeling — the follow-up reading is six types, number precision, and encoding pitfalls.

Can JSON arrays and objects be converted into each other?

Yes, but not losslessly. Converting an object to an array usually means turning keys into values and losing key-based lookup; converting an array to an object means inventing a key for every element, and where those keys come from is a new design problem. Decide based on how the consumer reads the data, not on what is syntactically convenient.

Can object keys be duplicated?

Syntactically yes — RFC 8259 only says keys SHOULD be unique. But JavaScript keeps the last value while some C-family libraries keep the first, so behavior differs across parsers. In signing, diffing, or hashing, duplicate keys cause direct disagreements. Avoid them on the producer side, and treat duplicates in untrusted input as a hazard on the consumer side.

Can an array hold values of different types?

Syntactically yes: [1, "a", true] is valid JSON. But heterogeneous arrays force type checks at every position in the consuming code, and they are hard to express in a schema. Except for matrices and tuples where position itself is the semantics, keep arrays homogeneous.

Why does {name:'json'} fail validation?

Because JSON requires double quotes around every key and every string value. {name:'json'} is a JavaScript object literal, not JSON. Change it to {"name": "json"} and it validates. Single quotes, bare keys, and comments belong to dialects like JSON5/JSONC, which need their own parsers rather than standard JSON.parse.