C.W.K.
Stream
Lesson 06 of 08 · published

Arrays — Ordered, Heterogeneous, No Trailing Comma

~10 min · json, arrays, ordering

Level 0Plaintext
0 XP0/64 lessons0/12 achievements
0/100 XP to next level100 XP to go0% complete

Arrays are ordered, square-bracketed, comma-separated

Arrays use [ and ]. Order is significant (unlike object keys). Elements can be any of the six types, and they don't have to be the same type — JSON arrays are heterogeneous in spec, even though most APIs use them homogeneously.

The trailing-comma trap

JSON does not allow a trailing comma after the last element. [1, 2, 3,] is a parse error. This is the single most common JSON syntax bug — Python, JavaScript, Rust, Go all allow trailing commas in their native literal syntax, so the muscle memory keeps biting.

Empty array vs null vs missing key

Three different states: "items": [] means 'we know the list, it's empty'. "items": null means 'we don't know yet'. Omitting items entirely means 'this concept doesn't apply'. APIs that conflate these create bugs that take an afternoon to debug.

Principle: arrays carry order; objects carry name. If your data is naturally ordered (steps, log entries, search results), use an array. If it's naturally name-addressable (settings, fields, attributes), use an object. Don't store ordered data as an object and rely on key insertion order.

Code

Arrays — homogeneous and heterogeneous·json
{
  "strings": ["a", "b", "c"],
  "numbers": [1, 2, 3],
  "objects": [
    { "id": 1, "name": "alpha" },
    { "id": 2, "name": "beta" }
  ],
  "mixed": [1, "two", true, null, [3, 4]]
}
The trailing-comma trap·json
[
  1,
  2,
  3,
]

# ↑ Parse error. JSON forbids trailing commas.
# Python and JS allow them in native syntax — that's where the muscle memory lies.
# The fix:
[
  1,
  2,
  3
]
Empty / null / missing — three different things·json
{
  "known_empty":     [],
  "unknown_yet":     null,
  "explicit_value":  [1, 2, 3]
}

# A fourth state — the key is absent entirely. Treat 'absent' as
// 'this concept doesn't apply to this resource'. APIs should pick
// one convention per field and document it.

External links

Exercise

Take a CSV file you have lying around (any tabular data). Convert it to a JSON array of objects, with each row becoming an object keyed by column name. Notice that you've now committed to one interpretation of every column type (string vs number vs boolean). The CSV was schema-less; the JSON has an implicit schema. Where did you have to guess?

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.