JSON for Beginners: What It Is, How to Use It in APIs, and Common Errors
Complete beginner guide to JSON. Data types, syntax rules, working with APIs, and fixing the most common JSON errors.
What Is JSON and Why Is It Everywhere?
JSON (JavaScript Object Notation) is the data format that powers almost every web API, mobile app, and modern web service. When your weather app shows today's temperature, when you log into a website, when you place an order on Amazon — JSON is the format carrying that data between client and server.
JSON was created by Douglas Crockford in the early 2000s as a simpler alternative to XML. It won decisively because it is human-readable, machine-parseable, and natively supported in JavaScript.
JSON Data Types
JSON supports exactly 7 value types — no more, no less:
``json
{
"string": "Hello, World",
"integer": 42,
"decimal": 3.14,
"boolean_true": true,
"boolean_false": false,
"null_value": null,
"array": [1, "two", true, null],
"nested_object": {
"key": "value"
}
}
`
What JSON does NOT have: dates (use ISO 8601 strings like "2026-03-15"), undefined, functions, comments.
The Six JSON Syntax Rules
Rule 1: Keys must be double-quoted strings
`
{"name": "Ravi"} ✓
{name: "Ravi"} ✗ (key must be quoted)
{'name': "Ravi"} ✗ (must be double quotes)
`
Rule 2: String values use double quotes only
`
{"city": "Delhi"} ✓
{"city": 'Delhi'} ✗
`
Rule 3: No trailing commas
`
{"a": 1, "b": 2} ✓
{"a": 1, "b": 2,} ✗ (trailing comma)
[1, 2, 3] ✓
[1, 2, 3,] ✗
`
Rule 4: No comments (use JSON5 or JSONC if you need comments)
Rule 5: No undefined — use null for missing values
Rule 6: Lowercase booleans — true/false not True/False
Working with JSON in JavaScript
Parsing JSON string to object:
`javascript
const jsonString = '{"name":"Ravi","age":30}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // 'Ravi'
`
Converting object to JSON string:
`javascript
const data = { name: 'Ravi', age: 30 };
const json = JSON.stringify(data);
// '{"name":"Ravi","age":30}'
// Pretty-printed with 2-space indentation
const pretty = JSON.stringify(data, null, 2);
`
Handling parse errors safely:
`javascript
function safeJSONParse(str) {
try {
return JSON.parse(str);
} catch (e) {
console.error('Invalid JSON:', e.message);
return null;
}
}
`
Fetching JSON from an API
`javascript
// Modern approach with async/await
async function fetchWeather(city) {
const response = await fetch(https://api.example.com/weather?city=${city});
if (!response.ok) {
throw new Error(HTTP error: ${response.status});
}
const data = await response.json(); // Automatically parses JSON
return data;
}
`
Common JSON API Error Handling
`javascript
async function callAPI(url) {
try {
const res = await fetch(url);
const contentType = res.headers.get('content-type');
// Verify it's actually JSON
if (!contentType?.includes('application/json')) {
throw new Error('Response is not JSON');
}
const data = await res.json();
// Check for API-level errors in the response body
if (data.error) {
throw new Error(data.error.message);
}
return data;
} catch (e) {
console.error('API call failed:', e);
throw e;
}
}
`
Common JSON Errors and Fixes
| Error | Cause | Fix |
|---|---|---|
| SyntaxError: Unexpected token | Trailing comma or missing quote | Remove trailing comma; add missing quotes |
| SyntaxError: Unexpected end | Unclosed bracket or brace | Count opening vs closing { } [ ] |
| SyntaxError: Unexpected token ' | Single quotes instead of double | Replace all ' with " around strings |
| undefined vs null | null is valid JSON, undefined is not | Use null for missing values |
JSONPath: Querying Nested JSON
For complex nested responses, JSONPath lets you extract values:
`
$.users[0].name — first user's name
$.products[*].price — all product prices
$.orders[?(@.total > 100)] — orders over 100
``
Formatting JSON with Lazyblink
When working with API responses, minified JSON is impossible to read. Paste any JSON string at lazyblink.com/tools/developer/json-formatter for instant formatting with syntax highlighting and error detection.
Frequently asked questions
What is JSON used for?
JSON is the primary data format for web APIs, configuration files, and data exchange between applications. When a mobile app fetches data from a server, or when two web services communicate, JSON is almost always the format.
What is the difference between JSON and JavaScript object?
JSON is a text format (string). A JavaScript object is data in memory. JSON.parse() converts JSON text to a JavaScript object. JSON.stringify() converts a JavaScript object to JSON text.
Why does my JSON give a SyntaxError?
The most common causes are: trailing commas after the last item in objects or arrays, single quotes instead of double quotes, unquoted keys, or missing closing brackets or braces.
Put this guide into practice with our free online tool — no signup required.
Open tool