JSON Syntax and Structure

1

JSON Syntax and Structure

▶

JSON, which stands for JavaScript Object Notation, is a lightweight, text-based data interchange format that has become the dominant standard for transmitting structured data across the web. It was derived from the object literal syntax of JavaScript, but it is entirely language-independent — virtually every modern programming language has libraries capable of parsing and generating JSON. Its popularity stems from a simple but powerful combination of qualities: it is compact, it is human-readable, and it maps naturally onto the data structures (objects and arrays) that developers work with every day.

When a web browser requests data from a server — for example, fetching a user's profile or a list of products — the server almost always responds with a JSON string. The browser's JavaScript engine can parse that string into native objects and work with the data immediately. Despite this close relationship with JavaScript, it is important to understand a fundamental distinction: JSON is a string. It is a textual representation of structured data, not a live JavaScript object. A JavaScript object can contain functions, undefined values, and other constructs that have no JSON equivalent. JSON is a strict, portable subset of notation that any language can read and write.

JSON is also written as plain text, which means you can open a .json file in any text editor, read it without special tools, and spot errors by eye. This transparency makes debugging and logging significantly easier compared to binary formats like Protocol Buffers or MessagePack.

To work effectively with JSON, you need a solid understanding of the data types it supports, the rules for constructing objects and arrays, the formatting conventions that separate valid JSON from invalid JSON, and the way structures can be nested to represent complex real-world data.

JSON Data Types

Every value in a JSON document must belong to one of six permitted data types. Using any other type — for instance, a JavaScript function or a date object — is not valid JSON.

  • String: A sequence of Unicode characters enclosed in double quotes. Single quotes are not permitted. Strings support standard escape sequences such as \" for an embedded double quote, \\ for a backslash, \n for a newline, and \uXXXX for a Unicode code point. Example: "name": "Alice".
  • Number: An integer or floating-point value written without quotes. JSON numbers follow standard decimal notation and support scientific notation (e.g., 1.5e3). There is no separate integer type; 30 and 30.0 are both numbers. Example: "age": 30, "price": 9.99.
  • Boolean: Exactly one of the two literal values true or false, written in lowercase with no quotes. Capitalised variants like True or TRUE are invalid. Example: "active": true.
  • Null: The single literal value null, also in lowercase with no quotes. It represents an intentional absence of a value, distinct from an empty string or the number zero. Example: "middleName": null.
  • Object: An unordered collection of key-value pairs enclosed in curly braces {}. Objects are themselves valid values, enabling nesting.
  • Array: An ordered list of values enclosed in square brackets []. Arrays are also valid values and can be nested freely.

The table below summarises these types with concise examples:

Type Example Value Notes
String "Hello, world!" Must use double quotes
Number 42, 3.14, -7, 2e10 No quotes; integers and decimals both valid
Boolean true, false Lowercase literals only
Null null Represents intentional absence of value
Object {"key": "value"} Unordered key-value pairs
Array [1, 2, 3] Ordered list; preserves sequence

JSON Objects

A JSON object is an unordered set of key-value pairs wrapped in curly braces. It is the most commonly encountered JSON structure and directly mirrors the concept of a dictionary, map, or hash in most programming languages. The rules for writing a valid JSON object are precise and must be followed exactly.

  • Keys must be strings in double quotes. Unlike JavaScript object literals, where keys can be unquoted identifiers, JSON requires every key to be a double-quoted string. Writing {name: "Alice"} is not valid JSON; you must write {"name": "Alice"}.
  • Each key is followed by a colon (:), then its associated value.
  • Pairs are separated by commas. There must be no trailing comma after the last key-value pair.
  • Values can be any valid JSON type, including another object, enabling nesting.

Here is a straightforward JSON object representing a person:

{
  "firstName": "Alice",
  "lastName": "Johnson",
  "age": 34,
  "isEmployed": true,
  "nickname": null
}

Notice that there is no comma after the last pair ("nickname": null). Adding one would make the document invalid. Also observe that each key — "firstName", "lastName", etc. — is enclosed in double quotes.

Objects can be nested: the value associated with a key can itself be a JSON object. For example, an address can be represented as a nested object inside a person object:

{
  "firstName": "Alice",
  "age": 34,
  "address": {
    "street": "12 Maple Avenue",
    "city": "Springfield",
    "postalCode": "62701"
  }
}

The "address" key holds an entire object as its value. That inner object follows exactly the same rules as the outer one.

JSON Arrays

A JSON array is an ordered list of values enclosed in square brackets. Order is meaningful — the first element is always the first element, and parsers are required to preserve that sequence. Arrays are ideal for representing collections of items: a list of tags, a series of measurements, or a roster of users.

  • Elements can be any valid JSON type, including strings, numbers, booleans, null, objects, or other arrays.
  • Elements are separated by commas, and as with objects, a trailing comma after the last element is not permitted.
  • Arrays preserve order, so the position of each element carries meaning.
  • A single array may contain mixed types, though in practice most arrays hold elements of a consistent type for clarity.

A simple array of strings:

["red", "green", "blue"]

An array of numbers:

[10, 20, 30, 40, 50]

A particularly common pattern is an array of objects, which represents a list of structured records. The following example shows an array of two user objects:

[
  {
    "id": 1,
    "username": "alice",
    "active": true
  },
  {
    "id": 2,
    "username": "bob",
    "active": false
  }
]

This structure is exactly what a REST API might return when a client requests a list of users. Each element in the array is a complete, self-contained JSON object, and together they form an ordered collection.

Arrays can also be nested within arrays. A two-dimensional grid of numbers, for instance, could be represented as:

[
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]

JSON Formatting Conventions

Valid JSON is governed by a strict set of syntactic rules. Violating any of them produces a document that cannot be parsed. These rules are worth memorising, because even a single misplaced character will cause an error.

  • Double quotes only. All string keys and all string values must be wrapped in double quotes ("). Single quotes (') are not valid in JSON under any circumstances.
  • No trailing commas. A comma must appear between consecutive elements or pairs, but not after the last one. Many developers transitioning from JavaScript make this mistake because modern JavaScript tolerates trailing commas; JSON does not.
  • No comments. JSON has no comment syntax. Adding // ... or /* ... */ anywhere in a JSON document immediately makes it invalid. If you need to annotate JSON configuration files, some tools support a superset like JSON5 or JSONC, but those are not standard JSON.
  • Whitespace is insignificant. Spaces, tabs, and newlines can be inserted freely between tokens for readability. The compact form {"a":1,"b":2} and the indented form below are semantically identical:
{
  "a": 1,
  "b": 2
}
  • A single root element. Every valid JSON document has exactly one root element. That root can be an object, an array, a string, a number, a boolean, or null — but there can only be one of them at the top level. You cannot place two separate objects side by side at the root.
  • Case sensitivity. JSON is case-sensitive. The key "Name" and the key "name" are two entirely different keys. Similarly, True is not a valid boolean; only true is.

The following example highlights several common errors and their corrections:

Invalid JSON Problem Corrected JSON
{name: "Alice"} Key not in double quotes {"name": "Alice"}
{'name': 'Alice'} Single quotes used {"name": "Alice"}
{"name": "Alice",} Trailing comma {"name": "Alice"}
{"active": True} Boolean not lowercase {"active": true}
{"score": .5} Number must start with digit {"score": 0.5}
// comment
{"x": 1}
Comments not allowed {"x": 1}

Nested Structures in JSON

One of JSON's greatest strengths is its ability to represent hierarchical, real-world data through nesting. Objects can contain arrays, arrays can contain objects, and both can go multiple levels deep. Each nested level obeys exactly the same syntax rules as the top level, so once you understand the basic structure, you can read and write arbitrarily complex documents.

Consider a JSON document representing a company. A company has a name, a founding year, a list of departments, and each department has its own name and a list of employees. Each employee has a name, a role, and a set of skills:

{
  "company": "Acme Corp",
  "founded": 1947,
  "departments": [
    {
      "name": "Engineering",
      "employees": [
        {
          "name": "Alice",
          "role": "Backend Developer",
          "skills": ["Python", "SQL", "Docker"]
        },
        {
          "name": "Bob",
          "role": "Frontend Developer",
          "skills": ["JavaScript", "CSS", "React"]
        }
      ]
    },
    {
      "name": "Marketing",
      "employees": [
        {
          "name": "Carol",
          "role": "Campaign Manager",
          "skills": ["SEO", "Analytics"]
        }
      ]
    }
  ]
}

Walking through this structure: the root is a JSON object with three keys. The "departments" key holds an array. Each element of that array is an object with a "name" key (a string) and an "employees" key (another array). Each element of the employees array is itself an object containing a "skills" key whose value is an array of strings. This is three levels of nesting, and every level follows the same fundamental rules.

While nesting can go arbitrarily deep, practical wisdom suggests keeping structures as flat as reasonably possible. Deeply nested JSON becomes difficult to read, harder to maintain, and can complicate the parsing code on the receiving end. When you find yourself five or six levels deep, it may be worth reconsidering the data model.

It is also worth noting that when objects contain arrays and arrays contain objects in the same structure, you gain the full expressive power needed to model almost any real-world dataset — from configuration files and API responses to database exports and inter-service communication payloads. JSON's simplicity is not a limitation; it is precisely what makes it so universally interoperable.

NotesAn exploration of the rules and structure of valid JSON, including data types, objects, arrays, and formatting conventions.