JSON (JavaScript Object Notation) is a text format for storing and exchanging data. Itβs how computers send data to each other over the internet β when you load a website, the API responses are almost always JSON.
It looks like this:
{
"name": "Alice",
"age": 30,
"developer": true,
"languages": ["JavaScript", "Python", "Go"],
"address": {
"city": "Brussels",
"country": "Belgium"
}
}
Thatβs it. If you can read the above, you can read JSON.
The rules
JSON has very few rules, which is why itβs so popular:
- Data is in key-value pairs:
"name": "Alice" - Keys must be strings in double quotes:
"name"notnameor'name' - Values can be: string, number, boolean, null, array, or object
- Strings use double quotes:
"hello"not'hello' - No trailing commas: the last item canβt have a comma after it
- No comments: JSON doesnβt support comments (this annoys everyone)
Data types
{
"string": "Hello world",
"number": 42,
"decimal": 3.14,
"boolean": true,
"nothing": null,
"array": [1, 2, 3],
"object": {
"nested": "value"
}
}
Thatβs every type JSON supports. No dates, no functions, no undefined.
Common mistakes
// β Single quotes
{'name': 'Alice'}
// β
Double quotes
{"name": "Alice"}
// β Trailing comma
{"name": "Alice", "age": 30,}
// β
No trailing comma
{"name": "Alice", "age": 30}
// β Comments
{
"name": "Alice" // this is a comment
}
// β
No comments allowed in JSON
{
"name": "Alice"
}
Reading JSON in JavaScript
// Parse JSON string β JavaScript object
const data = JSON.parse('{"name": "Alice", "age": 30}');
console.log(data.name); // "Alice"
// JavaScript object β JSON string
const json = JSON.stringify({ name: "Alice", age: 30 });
console.log(json); // '{"name":"Alice","age":30}'
// Pretty print
const pretty = JSON.stringify(data, null, 2);
Reading JSON in Python
import json
# Parse JSON string β Python dict
data = json.loads('{"name": "Alice", "age": 30}')
print(data["name"]) # Alice
# Python dict β JSON string
text = json.dumps({"name": "Alice", "age": 30})
# Pretty print
text = json.dumps(data, indent=2)
# Read from file
with open("data.json") as f:
data = json.load(f)
# Write to file
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
Where youβll see JSON
- API responses: almost every web API returns JSON
- Config files:
package.json,tsconfig.json, VS Code settings - Databases: MongoDB stores JSON documents, PostgreSQL has a JSONB type
- Data exchange: any time two systems need to share structured data
JSON vs. YAML vs. XML
| JSON | YAML | XML | |
|---|---|---|---|
| Readability | Good | Best | Worst |
| Comments | No | Yes | Yes |
| Data types | Basic | Rich | Strings only |
| Used for | APIs, config | Config, CI/CD | Legacy systems |
JSON won the API world because itβs simple, fast to parse, and works natively in JavaScript. YAML is preferred for config files because it supports comments and is easier to read.
See also: YAML cheat sheet and the JSON Formatter tool for pretty-printing and validating JSON.