Developer & Network Tools

JSON Explained With Examples

Read and write JSON with confidence: its six value types, nesting, common syntax errors, parsing code and validation.

Key takeaways

  • JSON has six kinds of value: object, array, string, number, Boolean and null.
  • Strings and object names must use double quotes, and trailing commas and comments aren't allowed.
  • Despite the name, JSON is language independent, and nearly every programming language can read and write it.
  • Parse JSON with a proper library; never evaluate it as program code.
  • Large integers, dates and missing values need agreed rules, because the format doesn't settle them for you.

JSON, short for JavaScript Object Notation, is a plain text format for structured data. It writes information as objects made of named values, and arrays made of ordered values, which can be nested inside one another. Web APIs, configuration files and many apps use it to store and exchange data.

If you can read this, you can already read most of it:

{
  "name": "Corner Cafe",
  "open": true,
  "seats": 24,
  "tags": ["coffee", "wifi"],
  "address": {"city": "Springfield", "postcode": "00123"},
  "website": null
}

The six types

JSON is standardized in RFC 8259 and in ECMA-404. The whole grammar is small.

Type Example Notes
Object {"id": 7} Name and value pairs in braces
Array [1, 2, 3] Ordered list in square brackets
String "hello" Double quotes only
Number -12.5, 3e8 No quotes, no leading +
Boolean true, false Lowercase
Null null Deliberately empty

There's no date type, no function type and no way to express "undefined". Anything else has to be represented with these six.

The six kinds of JSON value
A value Every JSON document is one value, often an object. Null Intentionally no value. Boolean true or false. Number Integer or decimal. Object Named values in { }. Array Ordered values in [ ]. String Text in double quotes. A value Every JSON document is one value, often an object. Object Named values in { }. Array Ordered values in [ ]. String Text in double quotes. Number Integer or decimal. Boolean true or false. Null Intentionally no value.

Objects, arrays and nesting

An object collects related facts under names. Each name is a string, followed by a colon and a value, with commas between pairs. The order of pairs isn't meant to carry meaning.

An array is a list where order does matter. Its items are usually of the same kind, such as a list of orders, though the format doesn't require it.

Because any value can be another object or array, you can describe trees of data:

{
  "order": 1042,
  "items": [
    {"sku": "CAB-2M", "qty": 2},
    {"sku": "PLUG-C", "qty": 1}
  ]
}

Programmers describe a location in this tree as a path. In JavaScript, data.items[0].sku gives "CAB-2M", because arrays count from zero.

Parts of one JSON object
{ } 1 "qty" 2 : 3 2 4 , 5 Object Braces open and close a set of named values. 1 Name Always a string in double quotes. 2 Colon Separates a name from its value. 3 Value A number here. Quoting it would make it text. 4 Comma Goes between entries, never after the last one. 5 { } 1 "qty" 2 : 3 2 4 , 5 Object Braces open and close a set of named values. 1 Name Always a string in double quotes. 2 Colon Separates a name from its value. 3 Value A number here. Quoting it would make it text. 4 Comma Goes between entries, never after the last one. 5

Strings and escaping

A string can contain any Unicode text, but a few characters need a backslash in front.

To include Write
Double quote \"
Backslash \\
Newline \n
Tab \t
Any code unit \u00e9

Windows file paths are a frequent trap: "C:\new\table" turns \n into a newline and \t into a tab. Write "C:\\new\\table" instead.

JSON exchanged between systems should be encoded as UTF-8, explained in ASCII, Unicode and UTF-8. Binary data such as an image can't go in directly, so it's usually converted with Base64.

The errors everyone makes

Many things that are fine in JavaScript or Python are invalid JSON:

  • Single quotes: {'name': 'x'}
  • Unquoted names: {name: "x"}
  • A trailing comma: [1, 2, 3,]
  • Comments with // or /* */
  • True, False or None in Python style
  • NaN, Infinity or undefined
  • Numbers with leading zeros, such as 007
  • A literal line break inside a string

Parser messages typically give a line and column. Look at that spot and just before it, since a missing comma or quote is often reported at the next token. A JSON formatter indents the text and points at problems.

Some programs accept relaxed variants, such as JSON5 or "JSON with comments" in editor settings files. Those are different formats, and a strict parser will reject them.

Reading and writing it in code

Use your language's parser. In JavaScript:

const data = JSON.parse(text);
const out  = JSON.stringify(data, null, 2);

In Python:

import json
data = json.loads(text)
out = json.dumps(data, indent=2, ensure_ascii=False)

On the command line, the jq tool filters and formats JSON. If it's installed, jq '.items[].sku' order.json lists each item's code in Bash. PowerShell has ConvertFrom-Json and ConvertTo-Json; for nested data, give ConvertTo-Json a larger -Depth, because the default is shallow.

Never build JSON by gluing strings together, and never run it through eval. A library handles escaping correctly and treats the input only as data.

Traps that pass validation

Valid JSON can still be misread.

Large integers. JavaScript stores numbers as double precision floating point, which holds integers exactly only up to 9,007,199,254,740,991. A longer ID can be silently rounded. Send such values as strings.

Money. Binary floating point can't represent many decimals exactly. Use an integer count of the smallest unit, or a decimal string that both sides parse with a decimal type.

Dates. Agree on a format. ISO 8601 text such as "2026-12-05T14:30:00Z" is readable and unambiguous. Bare numbers need a stated unit; see Unix timestamps.

Duplicate names. The standard says names should be unique. Parsers differ on what happens when they aren't, often keeping the last one.

Missing versus null versus empty. An absent field, null, "" and [] can all mean different things. Decide and document which you use.

Checking structure with a schema

Syntax checking confirms that text is JSON. It doesn't confirm that qty exists and is a positive integer. JSON Schema is a widely used vocabulary, itself written in JSON, for describing required fields, types and limits:

{
  "type": "object",
  "required": ["sku", "qty"],
  "properties": {
    "sku": {"type": "string"},
    "qty": {"type": "integer", "minimum": 1}
  }
}

Validate anything that arrives from outside before using it. API descriptions in the OpenAPI format use closely related schemas, which you'll meet when reading API documentation.

Designing JSON that others can use

When you define the shape yourself, a few habits save everyone trouble later.

  • Pick one naming style, such as camelCase or snake_case, and use it everywhere.
  • Make the top level an object, even when you return a list. {"items": [...]} leaves room to add a page marker or a count later without breaking anyone.
  • Keep a field's type constant. A value that's sometimes a string and sometimes an array forces special cases in every program that reads it.
  • Prefer arrays of objects over objects keyed by data. [{"sku": "CAB-2M", "qty": 2}] is easier to validate than {"CAB-2M": 2}, and it can grow new fields.
  • Put units in the name where they could be confused, as in timeoutSeconds or weightGrams.
  • Use real Booleans, not "yes", "no" or 1.

When you must change a published shape, add new fields and leave old ones in place for a while. Readers should ignore fields they don't recognize, which lets the producer grow the format safely.

A debugging walkthrough

Suppose a program reports Unexpected token while reading a settings file:

{
  "theme": "dark",
  "recent": [
    "notes.txt",
    "todo.txt",
  ],
  'zoom': 1.25
}

There are two faults. The comma after "todo.txt" has nothing following it inside the array, and 'zoom' uses single quotes. A parser stops at the first one, so after fixing it you'd see a second error. Run the check again after every change.

If a file looks perfectly correct and still fails on its first character, suspect something invisible. Some Windows editors and tools add a byte order mark at the start of a UTF-8 file, and some parsers reject it. Another frequent case is a program expecting JSON that actually received an HTML error page; the complaint about an unexpected < is the clue. Print the first part of the raw response before blaming the parser.

Curly quotation marks pasted from a word processor cause the same kind of puzzle, since they aren't the plain " character that JSON requires. Edit JSON in a code or plain text editor.

Security and size

Data from outside is untrusted even when it parses. Check types and ranges, limit how large a request body you'll accept, and watch for extremely deep nesting, which can exhaust some parsers. When you display a value on a web page, escape it for that context, since a JSON string can contain markup.

Very large documents are slow to load all at once, because a standard parser builds the whole tree in memory. Streaming parsers read piece by piece, and line-delimited files avoid the problem entirely. Compression during transfer helps a great deal too, since repeated field names compress well.

JSON Lines, also called newline-delimited JSON, puts one complete JSON value on each line. It suits logs and large exports, because a program can process one record at a time without loading the whole file.

When a server sends JSON over the web, it labels it with the Content-Type: application/json header, part of the exchange described in HTTP requests and responses.

For hand-edited configuration, formats that allow comments may be friendlier; XML, YAML and TOML compares them. For flat tables, CSV is smaller, and you can convert with CSV to JSON or JSON to CSV. Keep in mind that nested structures don't flatten into rows without choices about what to repeat or drop.

Written for 4Internet with AI writing tools and not reviewed line by line by a person. Check anything you rely on with the maker, provider or standard concerned. Report an error.

Keep reading

All 45 articles in Developer & Network Tools →

Latest news on this topic