JSON Tutorial: What It Is and How to Read It
JSON is everywhere. APIs return it, config files use it, databases store it. If you have ever copied text from an API and seen something that looked like {"name":"Alice","age":30} and wondered what it means, this guide is for you. We will cover the structure from scratch, walk through every data type, show the most common mistakes, and show you how to read any JSON file in minutes.
What Is JSON?
JSON stands for JavaScript Object Notation. It is a lightweight text format for storing and exchanging structured data. Despite the "JavaScript" in the name, JSON is completely language-independent — it is used in Python, Ruby, Go, PHP, Java, Swift, and virtually every other programming language.
The reason JSON became the dominant data format is simplicity. It is human-readable, compact, and maps naturally to the data structures (objects and arrays) that exist in nearly every language. Before JSON, XML was the standard — and JSON largely replaced it because XML is verbose and harder to read.
The Basic Structure: Key-Value Pairs
A JSON object is a collection of key-value pairs wrapped in curly braces { }. Each key is a string in double quotes, followed by a colon, followed by the value:
{
"name": "Alice",
"age": 30,
"city": "London"
}
Rules to remember:
- Keys must always be in double quotes (not single quotes).
- Key-value pairs are separated by commas.
- The last pair in an object has no trailing comma — this is one of the most common mistakes.
JSON Data Types
JSON supports six data types. Understanding each is essential for reading any JSON document:
| Type | Example | Notes |
|---|---|---|
| String | "hello world" | Always double-quoted |
| Number | 42 or 3.14 | No quotes — integer or float |
| Boolean | true or false | Lowercase, no quotes |
| Null | null | Represents no value |
| Object | {"key": "value"} | Nested key-value pairs |
| Array | [1, 2, 3] | Ordered list of values |
Arrays in JSON
An array is an ordered list of values wrapped in square brackets [ ]. Values are separated by commas. Array items can be any data type — including other objects or arrays:
{
"fruits": ["apple", "banana", "orange"],
"scores": [95, 87, 72],
"active": [true, false, true]
}
To access the second fruit, most languages use zero-based indexing: fruits[1] returns "banana".
Nesting: Objects Inside Objects
JSON objects can contain other objects as values. This is called nesting and is how complex data structures are represented:
{
"user": {
"id": 1,
"name": "Alice",
"address": {
"street": "10 Main St",
"city": "London",
"postcode": "SW1A 1AA"
}
}
}
To access the city, you would traverse: user → address → city. In JavaScript that is data.user.address.city.
Valid vs Invalid JSON
JSON has strict syntax rules. A single mistake renders the entire document invalid and will cause a parse error. The most common mistakes are:
- Trailing comma —
{"name": "Alice",}is invalid (comma after the last item). - Single quotes —
{'name': 'Alice'}is invalid. JSON requires double quotes. - Unquoted keys —
{name: "Alice"}is invalid. Keys must be quoted. - Comments — JSON does not support comments.
// this is a commentwill break parsing. - Mismatched brackets — every
{needs a closing}and every[needs a].
How to Format and Validate JSON Online
When you receive a JSON blob from an API, it is often minified — everything on one line with no spaces. That makes it nearly impossible to read. Pasting it into the ToolsBox JSON Formatter instantly reformats it with clean indentation and highlights any syntax errors.
- Copy your JSON text.
- Paste it into the JSON Formatter.
- Click Format — the output is properly indented and colour-coded.
- If there is an error, the tool shows the exact position of the problem so you can fix it.
- Use Minify to compress it back to a single line when needed.
JSON in JavaScript: Parse and Stringify
In JavaScript, two built-in methods handle JSON conversion:
// Convert a JSON string into a JavaScript object
const jsonString = '{"name":"Alice","age":30}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // "Alice"
// Convert a JavaScript object into a JSON string
const user = { name: "Bob", active: true };
const json = JSON.stringify(user);
console.log(json); // '{"name":"Bob","active":true}'
// Pretty-print with indentation (for readability)
console.log(JSON.stringify(user, null, 2));
// {
// "name": "Bob",
// "active": true
// }
JSON.parse() throws a SyntaxError if the string is not valid JSON. Always wrap it in a try/catch when parsing untrusted data from APIs or user input.
JSON vs JavaScript Objects: Key Differences
JSON looks almost identical to a JavaScript object literal but has stricter rules:
| Feature | JSON | JavaScript Object |
|---|---|---|
| Key quoting | Must use double quotes | Quotes optional (unless special chars) |
| String values | Must use double quotes | Single or double quotes |
| Trailing commas | Not allowed | Allowed (ES5+) |
| Comments | Not supported | Allowed |
| Functions as values | Not supported | Allowed |
| undefined values | Not supported (use null) | Allowed |
Working With JSON in Other Languages
JSON parsing is built into every modern language's standard library:
# Python
import json
data = json.loads('{"name": "Alice", "age": 30}')
print(data["name"]) # Alice
print(json.dumps(data, indent=2)) # pretty-print
# PHP
$obj = json_decode('{"name": "Alice", "age": 30}');
echo $obj->name; // Alice
echo json_encode($obj, JSON_PRETTY_PRINT);
# Python — write JSON to file
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
JSON Schema: Validating JSON Structure
JSON Schema is a standard for defining the expected structure of a JSON document — what keys are required, what types values must be, and what constraints apply. It is used for API documentation, form validation, and automated testing. A simple JSON Schema looks like this:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["name", "age"],
"properties": {
"name": { "type": "string" },
"age": { "type": "integer", "minimum": 0 }
}
}
This schema requires a JSON object with a name string and an age non-negative integer. Any document missing these keys or using wrong types will fail validation. JSON Schema validators are available for every major language.
Format and validate your JSON — free
Beautify, minify or fix syntax errors in seconds. No signup, runs in your browser.Where You Will Encounter JSON
Once you know what JSON looks like, you will spot it everywhere:
- REST APIs — virtually all web APIs return JSON responses.
- Config files —
package.json,tsconfig.json, VS Code settings. - NoSQL databases — MongoDB stores documents as JSON-like BSON.
- Authentication tokens — JWT (JSON Web Tokens) use Base64-encoded JSON.
- Browser storage —
localStorageandsessionStorageoften store JSON strings.
Frequently Asked Questions
What does JSON stand for?
JSON stands for JavaScript Object Notation. Despite the name, it is completely language-independent and used across virtually every programming language as a standard data exchange format.
What is the difference between JSON and XML?
Both are text-based data formats. JSON is more compact, easier to read and natively supported in JavaScript without a parser. XML uses verbose opening and closing tags; JSON uses key-value pairs and brackets. JSON has largely replaced XML for web APIs because it is smaller and simpler to work with.
What are the most common JSON errors?
The most frequent mistakes: (1) trailing comma after the last key-value pair — {"a":1,} is invalid; (2) single quotes instead of double quotes — {'key':'value'} is invalid; (3) unquoted keys — {key: "value"} is invalid; (4) comments — JSON does not support // or /* */ comments; (5) mismatched brackets. All of these cause a SyntaxError when parsed.
How do I validate JSON online?
Paste your JSON into the ToolsBox JSON Formatter. Valid JSON formats cleanly; invalid JSON shows the exact character position of the syntax error so you can fix it immediately.
What is the difference between JSON and YAML?
Both are human-readable data serialisation formats. YAML is more compact (no brackets, indentation-based structure, supports comments) and is popular for config files (Docker Compose, GitHub Actions, Kubernetes). JSON is stricter, faster to parse, and universally supported by APIs and browsers. JSON can be converted to YAML and back without data loss — our JSON to YAML converter does this instantly.
Can JSON contain arrays of objects?
Yes. Arrays of objects are one of the most common JSON patterns — for example, a list of users from a database API. Each array element is a full object: [{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]. This structure maps directly to a table (rows of records) and is the standard format for API responses returning multiple items.
Is JSON secure to use in web applications?
JSON itself is just text — it cannot execute code. However, JSON data should never be inserted directly into HTML without sanitisation (to prevent XSS) and should never be eval()'d in JavaScript (use JSON.parse() instead). When receiving JSON from an API, always validate the structure before trusting the content.
← Back to Blog | Related tool: Free JSON Formatter