WebPiki
tutorial

JSON — The Data Format You Use Every Day

JSON structure, data types, API usage, comparison with XML/YAML, common mistakes, and practical tips.

Nested data structures represented as JSON

If you do any web development, you can't avoid JSON. API responses come back as JSON. Config files are JSON. LocalStorage stores JSON. It's the lingua franca between frontend and backend.

The Basics

JSON (JavaScript Object Notation) is a text format for storing and exchanging data. Despite the name, it's language-agnostic — Python, Java, Go, C#, Rust, they all use it.

The structure is straightforward:

{
  "name": "Jane Park",
  "age": 28,
  "skills": ["TypeScript", "React", "Node.js"],
  "employed": true,
  "address": null
}

Curly braces {} for objects, square brackets [] for arrays. Keys must be wrapped in double quotes. That's the biggest difference from JavaScript object literals — JS allows { name: "Jane" } but JSON requires { "name": "Jane" }.

Six Data Types

JSON supports exactly six types:

TypeExampleNotes
String"hello"Double quotes only
Number42, 3.14, -1Integer, float, negative
Booleantrue, falseLowercase only
nullnullAbsence of value
Object{ "key": "value" }Key-value pairs
Array[1, 2, 3]Ordered list of values

What's not here: undefined, functions, Date objects, NaN, Infinity. When you JSON.stringify something containing these, they either disappear or become null.

JSON.stringify({ a: undefined, b: NaN, c: Infinity })
// '{"b":null,"c":null}'
// `a` (undefined) is removed entirely

JSON and APIs

In the REST world, JSON is the de facto standard. You send it, you receive it.

// sending data
const response = await fetch("/api/users", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Jane", email: "jane@example.com" }),
});

// receiving data
const data = await response.json();

Forgetting the Content-Type: application/json header is a surprisingly common mistake. Some servers won't parse the body as JSON without it.

JSON vs Other Formats

JSON vs XML

XML came first. Here's the same data in both:

<user>
  <name>Jane Park</name>
  <age>28</age>
</user>
{
  "name": "Jane Park",
  "age": 28
}

JSON is more compact — XML's opening and closing tags add a lot of overhead. That's why web APIs migrated almost entirely to JSON. XML still lives on in SOAP services, RSS feeds, and SVG.

JSON vs YAML

YAML is technically a superset of JSON — all valid JSON is valid YAML.

name: Jane Park
age: 28
skills:
  - TypeScript
  - React

Config files tend to use YAML. Kubernetes manifests, GitHub Actions workflows, Docker Compose — all YAML. It's easier for humans to read and write. JSON is better for machines to parse and exchange.

JSON vs TOML

TOML is a config-file-specific format. Rust's Cargo.toml is the most well-known example.

[database]
host = "localhost"
port = 5432

Clean for flat configs, but deeply nested structures get awkward fast.

Common Mistakes

Trailing commas. A comma after the last item causes a parse error. JavaScript objects allow it; JSON does not.

{
  "a": 1,
  "b": 2,  // ← this comma breaks parsing
}

Single quotes. JSON only accepts double quotes. {'name': 'test'} is not valid JSON.

Comments. JSON has no comment syntax. No //, no /* */. This is annoying for config files, which is why JSONC (JSON with Comments) exists — VS Code's settings.json uses it.

Large numbers. JSON numbers are parsed as IEEE 754 floating point. Integers larger than 9007199254740991 (2^53 - 1, i.e. Number.MAX_SAFE_INTEGER) can lose precision. The workaround is to pass them as strings. That's why Twitter's API provides IDs as both "id": 12345 and "id_str": "12345".

Practical Tips

Pretty-printing with JSON.stringify. The third argument controls indentation.

JSON.stringify(data, null, 2);
// outputs with 2-space indentation

The replacer function. The second argument lets you filter or transform values.

JSON.stringify(data, (key, value) => {
  if (key === "password") return undefined; // strip passwords
  return value;
});

JSON.parse reviver. Transform values during parsing.

JSON.parse(text, (key, value) => {
  if (key === "date") return new Date(value);
  return value;
});

Useful for converting date strings to Date objects, since JSON has no native date type.

JSON Schema

JSON Schema defines the structure of JSON data — similar to TypeScript interfaces but for raw data validation.

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "integer", "minimum": 0 }
  },
  "required": ["name"]
}

It's used for API documentation, config file validation, and code generation. The autocomplete you get when editing JSON files in VS Code? That's JSON Schema at work.

Debugging JSON

When an API dumps a giant single-line response, reading it raw is painful. Browser dev tools format it automatically, and jq is the go-to CLI tool. For quick checks in the browser, a JSON Formatter lets you paste it in and see it properly indented, with syntax errors highlighted instantly.

# jq is your best friend on the command line
curl -s https://api.example.com/users | jq .

# extract specific fields
cat response.json | jq '.data[] | {name, email}'

Performance and Size

JSON is human-readable but verbose. Key names repeat for every object — if you have 1000 objects with the same structure, "name" and "age" appear 1000 times each.

Options for large-scale data:

  • gzip compression — Adding Content-Encoding: gzip to HTTP responses typically shrinks JSON by 70-80%. Most web servers handle this automatically.
  • Field selection — GraphQL lets clients request only the fields they need. REST APIs can implement this with query parameters like ?fields=name,email.
  • Binary formats — MessagePack, Protocol Buffers, and CBOR are smaller and faster to parse than JSON. Useful for service-to-service communication where performance matters.

For typical web APIs, JSON + gzip is plenty. Binary formats are overkill for most use cases.

JSON Lines (JSONL)

For log files and streaming data, JSON Lines is a practical variant. One JSON object per line.

{"timestamp": "2026-03-04T10:00:00Z", "level": "info", "message": "Server started"}
{"timestamp": "2026-03-04T10:00:01Z", "level": "error", "message": "DB connection failed"}

You can parse line by line without loading the entire file into memory. OpenAI's batch API and BigQuery data loading both use JSONL format.

At the end of the day, JSON is simple. Curly braces, square brackets, double quotes. Get those three right and you've got the fundamentals. The rest you pick up by using it.

#JSON#data format#API#web development#JavaScript

Related Posts