Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 39 ยท JSON

JSON Syntax and Data Types

Learn JSON syntax and its six data types, how JSON differs from JavaScript object literals, what it cannot hold and the most common syntax errors.

JSON (JavaScript Object Notation) is a text format for structured data. It is how most web APIs describe things: a user, a list of products, a weather forecast. A JSON document is just a string of characters that follows strict rules, so any language can read and write it. That is why a PHP server, a Python script and your browser can all exchange the same data.

Despite the name, JSON is not JavaScript. Its syntax was borrowed from JavaScript's object literals, but it is much stricter and smaller. Knowing exactly where the rules differ will save you hours of confusing SyntaxError messages. If you want a first look at the JavaScript side, JSON in JavaScript gives a short overview; this lesson goes deeper into the format itself.

The six value types

Every JSON value is one of exactly six things. Two are containers and four are simple values.

flowchart TB
    V["JSON value"] --> O["object<br/>{ key: value }"]
    V --> A["array<br/>[ value, value ]"]
    V --> S["string<br/>double quotes"]
    V --> N["number"]
    V --> B["boolean<br/>true / false"]
    V --> Z["null"]
    O -. contains .-> V
    A -. contains .-> V

Objects and arrays can contain any value, including more objects and arrays, which is how JSON nests.

Here is one document that uses all six:

JSON
{
  "name": "Ada Lovelace",
  "born": 1815,
  "height": 1.65,
  "active": false,
  "spouse": null,
  "languages": ["English", "French"],
  "address": { "city": "London", "country": "UK" }
}
  • Object: curly braces with comma-separated "key": value pairs. Keys must be strings in double quotes.
  • Array: square brackets with comma-separated values, in order. Items can be of different types.
  • String: text in double quotes.
  • Number: a decimal number, with an optional fraction and exponent (-3, 2.5, 6.02e23).
  • Boolean: the lowercase words true and false.
  • null: the lowercase word null, meaning "no value".

A complete JSON document can be any one of these. The text 42, "hello" and null are all valid JSON documents on their own, though APIs almost always send an object or an array.

String rules

Strings are where beginners trip most. A JSON string:

  • Must use double quotes. Single quotes are invalid.
  • Can contain any Unicode character, including emoji and accented letters.
  • Must escape the quote, the backslash and control characters (such as a newline). The allowed escapes are \", \\, \/, \b, \f, \n, \r, \t and \uXXXX (a four-digit hexadecimal code).

A raw line break is not allowed inside a string; it must be written as \n.

Number rules

JSON numbers are stricter than JavaScript's:

  • No leading zeros (007 is invalid).
  • No leading plus sign (+5 is invalid).
  • A digit is required on both sides of a decimal point (.5 and 5. are invalid; write 0.5 and 5.0).
  • No hexadecimal, no NaN, no Infinity.

JSON itself puts no limit on size or precision, but JavaScript reads every number as a 64-bit float. Integers above 2^53 - 1 (9007199254740991) can lose precision, which is why APIs often send huge ids such as database keys as strings.

Testing what is valid

The quickest way to learn the rules is to try them. JSON.parse() reads a JSON string and throws a SyntaxError if the text is not valid. (The next lesson covers JSON.parse in detail; here we only use it as a checker.) Run the demo and read which lines fail.

JS Valid or invalid JSON?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first five lines are valid and the rest fail. Every line in the second group is something that would be perfectly legal in a JavaScript object literal, which leads to the next point.

JSON versus a JavaScript object literal

At a glance they look the same, but they are different things: one is text, the other is a live object in memory.

JSON JavaScript object literal
Is it a string? Yes, text only No, it creates an object
Keys Always double-quoted strings Quotes optional; can be symbols or computed
String quotes Double only Single, double or backticks
Trailing commas Not allowed Allowed
Comments Not allowed Allowed
Values Six types only Functions, undefined, Date, Map, class instances and more

When you write const user = { name: "Ada" }, that is JavaScript and no JSON is involved. A JSON document only exists as a string, for example '{"name":"Ada"}', until you parse it into an object or after you serialize an object into one.

JS Same data, two different things

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What JSON cannot hold

JSON has no way to write many things JavaScript programs use every day. When you serialize such a value, it is changed or dropped silently:

JavaScript value What happens in JSON
undefined Omitted from objects, becomes null inside arrays
Functions and symbols Omitted from objects, null inside arrays
NaN, Infinity Become null
Date Becomes an ISO 8601 string (and stays a string when parsed back)
Map, Set Become {} (their contents are lost)
BigInt Throws a TypeError
Class instances Only own enumerable properties survive; the class is lost

There is no date type, no binary type and no comment syntax. Dates travel as strings (usually ISO 8601 like "2020-01-15T00:00:00.000Z"), binary data as base64 strings. Converting those back into real types is a job for your own code, which a later lesson shows how to do.

JS Round trips lose information

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JSON compared with XML, YAML, BSON and JSON Lines

JSON is not the only way to write structured data. Knowing the neighbors helps you choose, and read data from systems that do not speak JSON.

Format Looks like Strengths Weaknesses Typical MIME type
JSON {"name":"Ada"} tiny grammar, native in JavaScript, every language parses it no comments, no dates, no binary application/json
XML <user><name>Ada</name></user> attributes, namespaces, schemas (XSD), mixed content such as documents verbose, heavier to parse application/xml or text/xml
YAML name: Ada readable, comments, anchors and references indentation-sensitive, many surprises (a bare no can parse as false) application/yaml
BSON binary extra types (dates, binary, 64-bit integers, ObjectId), fast to scan not human-readable, bigger for small data application/bson
JSON Lines (NDJSON) one JSON value per line streams and appends; one bad line costs one record not a single document application/x-ndjson or application/jsonl
CSV id,name rows spreadsheets, tiny flat only, no types text/csv

How to choose:

  • Web APIs between a browser and a server: JSON. It is the default for a reason.
  • Configuration files that humans edit: YAML or TOML, or JSON with comments (see below), because people need to leave notes.
  • Documents with mixed text and markup, or systems that already use XML (SOAP, RSS, SVG, many enterprise formats): XML.
  • Databases that store documents: MongoDB stores BSON internally, but talks to you in JSON-like objects. You rarely write BSON by hand.
  • Logs and big exports: JSON Lines, so you can process one record at a time (see NDJSON).
JS The same record as JSON and XML

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The XML version needs a hand-written conversion because attributes and elements hold only text: you decide that id is a number and admin a boolean. JSON already carries those types. Converting from XML to JSON automatically is possible, but the mapping is not unique (is <tag>x</tag> an array of one item or a single value?), so agree on rules or use a library.

Two practical notes. In fetch, response.json() only works for JSON; for XML use response.text() followed by DOMParser. And YAML is almost a superset of JSON: most JSON files are also valid YAML, which is why tools that read YAML accept JSON, but a browser has no built-in YAML parser, so you would add a library such as js-yaml if you need one.

Comments in JSON, JSONC and JSON5

JSON has no comment syntax. Douglas Crockford, who specified it, removed comments because people were using them to carry parsing instructions, which hurt interoperability. The result: // note in a JSON file is a syntax error for JSON.parse.

Tempting workarounds are poor. A key like "_comment": "..." becomes real data that every consumer sees and may choke on, and it cannot sit between keys without being a property. Better options:

Option What it is Where you see it
JSONC ("JSON with Comments") JSON plus // and /* */ comments, often trailing commas VS Code settings, tsconfig.json
JSON5 a larger superset: comments, trailing commas, single quotes, unquoted keys, hex numbers, Infinity, NaN, multi-line strings config files, some build tools
YAML or TOML different formats with comments built in CI files, Cargo.toml, pyproject.toml

These are configuration formats, read by tools that know them. For data you send over HTTP, stay with strict JSON, because every client expects it.

To read JSONC or JSON5 in JavaScript, use a parser for the format. You can also strip comments yourself for simple cases, as long as you respect strings (a URL such as "http://x" contains // and must not be treated as a comment):

JS Stripping comments, and the JSON5 library

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last line matters: when you send data to a server, write it out as strict JSON with JSON.stringify, even if you read it from a relaxed file.

Common syntax errors and how to spot them

Almost every JSON error falls into a short list:

  1. Trailing comma after the last item: [1, 2,].
  2. Single quotes around strings or keys.
  3. Unquoted keys: { name: "Ada" }.
  4. Comments (// or /* */).
  5. Missing or extra comma between items, or a missing closing brace or bracket.
  6. Unescaped characters inside a string, such as a raw tab or newline, or a stray quote.
  7. Invalid numbers: leading zeros, NaN, .5.
  8. Text that isn't JSON at all, for example an HTML error page where JSON was expected.

Number 8 is the most common in AJAX work. When response.json() fails with a message such as "Unexpected token '<'", the server almost certainly returned an HTML page (a 404 or login page) that starts with <. Check the status and the Content-Type header before blaming your code.

Tip. Paste suspicious JSON into the browser console or a validator and fix the first error reported; later errors are often caused by the first one. Many editors also highlight JSON mistakes as you type.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which of these is valid JSON?

    JSON needs double-quoted keys and strings, no trailing comma and no undefined. Only the third option follows every rule.
  2. 2. How is a date normally represented in JSON?

    JSON has no date type. Dates are sent as strings, and your code converts them back into Date objects when needed.
  3. 3. What is the difference between JSON and a JavaScript object literal?

    JSON is a string format with six value types and strict syntax. An object literal is JavaScript code that creates an in-memory object.
  4. 4. response.json() fails with "Unexpected token '<'". What is the most likely cause?

    HTML starts with a less-than sign. Error pages and login pages are common culprits; check the status code and Content-Type.

Summary

  • JSON is a text format with six value types: object, array, string, number, boolean and null.
  • Keys and strings need double quotes; no trailing commas, comments, undefined, NaN or leading-zero numbers.
  • JSON is a string; a JavaScript object literal is a live object. They look similar but follow different rules.
  • Dates, Map, Set, BigInt, functions and class types have no JSON form and are dropped, flattened or rejected.
  • Most syntax errors are a short, predictable list; HTML where JSON was expected is the classic AJAX one.

Next: JSON.parse and JSON.stringify โ€” converting between text and objects.