Find a course

Module 2: JSON: The Language of APIsLesson 3 of 1213 min

JSON Syntax: Objects, Arrays and Values

Read and write JSON correctly: the six value types, objects and arrays, nesting, and the strict rules that make one stray comma break an entire response.

Step 1 of 15Learn

One format almost every API speaks

A server written in Java and a phone app written in Swift need a common language for data. Today that language is almost always JSON, short for JavaScript Object Notation. It was popularized in the early 2000s as a lighter alternative to XML, and it's now standardized (RFC 8259 and ECMA-404) and supported by every mainstream programming language.

Here is a book as JSON:

{
  "id": 42,
  "title": "The Silent River",
  "price": 14.99,
  "inStock": true,
  "tags": ["mystery", "bestseller"],
  "author": { "name": "R. Okafor", "born": 1979 },
  "subtitle": null
}

JSON's appeal is that it's readable by humans and trivial for programs to parse. It's also compact: no closing tags as in XML, just braces, brackets, colons and commas.

Despite the name, JSON isn't tied to JavaScript. It borrows JavaScript's object syntax, but it's a plain text format. Python reads it into dictionaries and lists, Java into objects or maps, and databases such as PostgreSQL can store and query it directly. JSON files are also everywhere outside APIs: configuration files such as package.json, data exports, logs and notebook files all use it.

Step 2 of 15Learn

The six kinds of values

Every piece of JSON is built from exactly six value types:

TypeExampleNotes
string"Oslo"Always in double quotes
number42, -3.5, 1.2e6No quotes; no leading zeros like 007; no NaN or Infinity
booleantrue, falseLowercase, no quotes
nullnullMeans "no value"; lowercase
object{"a": 1}Unordered set of key-value pairs in braces
array[1, 2, 3]Ordered list of values in brackets

Objects and arrays are containers: they can hold any values, including other objects and arrays, nested as deep as needed. In an object, each key must be a string in double quotes, followed by a colon and the value. Pairs are separated by commas. In an array, values are separated by commas and can be of mixed types, though good APIs keep each array's items the same shape.

Note what's missing: JSON has no date type. Dates travel as strings, usually in ISO 8601 format such as "2026-03-03T10:15:02Z". It has no undefined, no functions and no comments either. That small, strict feature set is exactly why every language can read it.

Step 3 of 15Practice · Sort into groups

Sort these JSON values by type.

Tap an item, then tap its group (or drag it there).

Step 4 of 15Practice · Diagram

The six JSON value types

Which type would you use for an ordered list of a customer's orders?

Tap the shape that answers the question, then press Check.

The six JSON value typesHierarchy diagram: JSON value, Simple values, string, number, boolean, null, Containers, object { }, array [ ].JSON valueSimple valuesstringnumberbooleannullContainersobject { }array [ ]
JSON value
Simple values
string

"Oslo" — always double quotes.

number

42, -3.5, 1.2e6 — no quotes, no leading zeros.

boolean

true or false, lowercase.

null

null: deliberately empty.

Containers

Hold other values, so they can nest.

object { }

Unordered "key": value pairs.

array [ ]

An ordered list of values.

Step 5 of 15Learn

The strict rules that trip people up

JSON looks like JavaScript, but it's stricter. These are all invalid JSON:

{ name: "Kim" }              keys must be in double quotes
{ 'name': 'Kim' }            single quotes are not allowed
{ "a": 1, "b": 2, }          trailing comma after the last pair
[1, 2, 3,]                   trailing comma in an array
{ "a": 1 } // comment        comments are not allowed
{ "price": .5 }              numbers need a digit before the point
{ "ok": True }               booleans must be lowercase
{ "n": undefined }           undefined does not exist in JSON

One stray character makes the whole document unparsable. A parser doesn't skip the bad line; it rejects everything and usually reports a position: "Unexpected token } in JSON at position 27".

Two more points:

  • Whitespace doesn't matter outside strings. A response may arrive minified on one line or pretty-printed over fifty; both mean the same thing.
  • Duplicate keys such as {"a": 1, "a": 2} are technically allowed by the grammar, but behavior differs between parsers (most keep the last value). Never rely on them.

When you hand-write JSON, for test data or a config file, paste it into a validator or let your editor check it. Most editors highlight JSON errors as you type.

Step 6 of 15Practice · Spot the mistake

This JSON is supposed to describe a user. Click every line that makes it invalid.

Step 7 of 15Learn

Nesting and paths

Real API responses nest objects and arrays several levels deep. Here's a trimmed order:

{
  "orderId": "A-1009",
  "customer": { "name": "Lee Park", "address": { "city": "Denver", "zip": "80202" } },
  "items": [
    { "sku": "MUG-01", "qty": 2, "price": 8.5 },
    { "sku": "TEE-L", "qty": 1, "price": 19.0 }
  ],
  "paid": true
}

To talk about one value, developers describe its path from the top:

  • the customer's city: customer.address.city → "Denver"
  • the first item's SKU: items[0].sku → "MUG-01" (arrays count from zero)
  • the number of items: the length of items → 2

A helpful reading habit: braces mean "look up by name", brackets mean "look up by position". When a path fails in code, it's usually because one step is wrong: treating an array as an object (items.sku) or an object as an array (customer[0]).

Designing JSON well matters too. Use consistent key style (camelCase like orderId or snake_case like order_id, not both), keep types stable (a price is always a number, never sometimes a string), and prefer arrays of objects for lists of records.

Step 8 of 15Practice · Fill in the blanks

Fill in the blanks

In the order above, the path to the quantity of the second item is items[].qty, and its value is . The path to the ZIP code is customer..zip

Step 9 of 15Practice · Work it out

Using the order above, what is the order total in dollars (sum of quantity × price for every item)?

Step 10 of 15Diagram

The order as a tree of paths

Every value has a path from the root. Dots step into objects, brackets pick array positions (counting from 0).

The order as a tree of pathsHierarchy diagram: order (object), orderId: "A-1009", customer (object), name: "Lee Park", address (object), city: "Denver", zip: "80202", items (array), items[0] (object), items[1] (object).order(object)orderId:"A-1009"customer(object)name:"LeePark"address(object)city:"Denver"zip:"80202"items(array)items[0](object)items[1](object)

Tap a shape with to see more.

order (object)
orderId: "A-1009"
customer (object)
name: "Lee Park"
address (object)
city: "Denver"

Path: customer.address.city

zip: "80202"

Path: customer.address.zip. Stored as a string so leading zeros survive.

items (array)
items[0] (object)

The first item: index 0.

items[1] (object)

The second item: index 1.

Step 11 of 15Note

Step 12 of 15Learn

JSON compared with XML, CSV and YAML

JSON isn't the only data format you'll meet around APIs.

XML was the dominant API format before JSON. It uses tags like HTML: <book><title>Tide Lines</title></book>. It's more verbose, but supports attributes, namespaces and powerful schema validation. Older enterprise and government systems, and the SOAP style, still use it widely.

CSV (comma-separated values) is a flat table: one record per line, fields separated by commas. It's excellent for spreadsheets and bulk exports, but it can't represent nesting, and every value is just text, so types must be guessed.

YAML is a human-friendly superset of JSON that uses indentation instead of braces. It's popular for configuration files, such as CI pipelines and OpenAPI descriptions, but rare as an API response format.

JSON hits a sweet spot for APIs: nesting like XML, far less noise, real types for numbers, booleans and null, and native support in browsers. That's why "REST API" and "JSON" are so often mentioned together, even though REST doesn't require JSON. Some APIs offer several formats from the same endpoint and let the client choose with the Accept header.

Step 13 of 15Practice · Match the pairs

Match each format to the description that fits it best.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. JSON
  2. XML
  3. CSV
  4. YAML

Step 14 of 15Compare

Four data formats side by side

AspectJSONXMLCSVYAML
NestingYesYesNo, flat rowsYes
Typed valuesStrings, numbers, booleans, nullEverything is text unless a schema says otherwiseEverything is textYes, inferred
CommentsNoYesNoYes
Typical homeWeb APIsOlder enterprise and SOAP servicesSpreadsheets and exportsConfig files

Step 15 of 15Practice · True or false

{"count": "5"} and {"count": 5} are equivalent JSON, because a parser converts quoted numbers automatically.