JavaScript JSON Explained — Complete Guide to Data Exchange
JSON (JavaScript Object Notation) is the universal data format for web APIs — it’s how browsers and servers exchange structured data in a lightweight, human-readable text format.
What You’ll Learn
- JSON syntax rules and how it differs from JavaScript objects
- Parsing JSON strings with
JSON.parse() - Converting objects to JSON with
JSON.stringify() - Handling JSON from APIs with Fetch
- Common JSON pitfalls: circular references, dates, special types
Why JSON Matters
Every modern web app communicates with a server — fetching user profiles, submitting forms, loading product catalogs. That data is almost always in JSON format. The Doda Browser uses JSON for extension manifests, bookmark exports, and sync data. The Durga Antivirus Pro dashboard receives threat intelligence feeds and scan results as JSON from its backend API. Without JSON, web applications would have no standard way to exchange data.
Learning Path
flowchart LR
A[JavaScript Objects] --> B[JSON]
B --> C[Async JS / Fetch API]
B --> D[Local Storage]
B --> E[REST APIs]
B --> F[You Are Here]
What Is JSON?
JSON is a text format for representing structured data. It looks like a JavaScript object but with stricter rules. Think of JSON as the “universal language” that any programming language can understand — like English for global communication.
Valid JSON
{
"name": "Alice",
"age": 25,
"isStudent": false,
"hobbies": ["reading", "coding"],
"address": {
"city": "NYC",
"zip": "10001"
},
"score": null
}JSON Rules (Strict!)
- Keys must be double-quoted strings — no single quotes, no unquoted keys
- Strings must use double quotes —
'Alice'is invalid,"Alice"is valid - No trailing commas —
{ "a": 1, }is invalid - No functions, undefined, or comments
- Valid types: string, number, boolean, null, object, array
JSON.parse() — String to Object
Convert a JSON string into a JavaScript value:
const json = '{"name":"Alice","age":25}';
const user = JSON.parse(json);
console.log(user.name); // 'Alice'
console.log(user.age); // 25
Safety: Always Wrap in try/catch
try {
const data = JSON.parse(malformedJson);
} catch (e) {
console.error('Invalid JSON:', e.message);
// Handle gracefully — show user-friendly error
}Never trust JSON from external sources. A malformed JSON string will throw a SyntaxError and crash your program.
Reviver Function
Transform values during parsing:
const json = '{"name":"Alice","birthDate":"2000-01-15"}';
const user = JSON.parse(json, (key, value) => {
if (key === 'birthDate') return new Date(value);
return value;
});
console.log(user.birthDate.getFullYear()); // 2000
JSON.stringify() — Object to String
Convert a JavaScript value into a JSON string:
const user = {
name: 'Alice',
age: 25,
role: 'admin',
skills: ['JS', 'CSS']
};
const json = JSON.stringify(user);
// '{"name":"Alice","age":25,"role":"admin","skills":["JS","CSS"]}'
Pretty-Printing
console.log(JSON.stringify(user, null, 2));
// {
// "name": "Alice",
// "age": 25,
// "role": "admin",
// "skills": ["JS", "CSS"]
// }
The third argument (2) is the indentation level. Use it for debugging or displaying JSON to users.
Replacer Function
Filter or transform values during stringification:
// Array of keys — only include these
JSON.stringify(user, ['name', 'age']);
// Function — exclude sensitive fields
JSON.stringify(user, (key, value) => {
return key === 'password' ? undefined : value;
});The toJSON Method
Objects can customize how they’re serialized:
const product = {
name: 'Widget',
price: 10,
toJSON() {
return { name: this.name }; // Only serialize name
}
};
console.log(JSON.stringify(product)); // '{"name":"Widget"}'
JSON & Arrays
const json = '[1, "two", true, null, {"key": "value"}]';
const arr = JSON.parse(json);
// Array of objects — common API response format
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
console.log(JSON.stringify(users));
// '[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]'
JSON from Servers (Fetch API)
async function loadUsers() {
try {
const res = await fetch('/api/users');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const users = await res.json();
return users;
} catch (error) {
console.error('Failed to load users:', error);
return [];
}
}Line by line:
fetch('/api/users')— Send a GET request to the serverres.ok— Check if the HTTP status is in the 200-299 rangeawait res.json()— Read the response body and parse it as JSONreturn users— Return the parsed JavaScript array
JSON & Local Storage
// Save an object
const settings = { theme: 'dark', fontSize: 14 };
localStorage.setItem('settings', JSON.stringify(settings));
// Load and parse
const saved = JSON.parse(localStorage.getItem('settings'));
console.log(saved.theme); // 'dark'
Common Mistakes
1. Trailing commas in JSON
JSON.parse('{"name":"Alice",}'); // SyntaxError!
JSON is stricter than JavaScript objects — no trailing commas allowed.
2. Trying to stringify circular references
const obj = { a: 1 };
obj.self = obj;
JSON.stringify(obj); // TypeError: Converting circular structure to JSON
Fix: Remove circular references before stringifying, or use a library like flatted.
3. Single quotes in JSON
JSON.parse("{'name': 'Alice'}"); // SyntaxError!
Always use double quotes for strings and keys in JSON.
4. Not wrapping JSON.parse in try/catch
Network data can be corrupted, truncated, or malformed. Always handle parse errors.
5. Functions and undefined are lost in stringify
JSON.stringify({ fn: () => {}, val: undefined });
// '{}' — both are omitted
JSON has no representation for functions or undefined. They’re silently dropped.
6. Using eval to parse JSON
const data = eval('(' + json + ')'); // DANGEROUS! Executes arbitrary code
Always use JSON.parse() — it’s safe, fast, and never executes code.
Practice Questions
What are the valid JSON data types? String, number, boolean, null, object, array. No functions, undefined, or symbols.
What’s the difference between JSON and a JavaScript object literal? JSON keys must be double-quoted. JSON has no functions, undefined, or trailing commas.
How do you pretty-print JSON?
JSON.stringify(obj, null, 2)— the third argument is indentation level.Why should you wrap
JSON.parsein try/catch? Malformed input throws a SyntaxError. try/catch lets you handle it gracefully.
Challenge: Create an array of product objects, serialize it to JSON, save to localStorage, then read it back and display the product names on the page.
FAQ
Try It Yourself
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON Playground</title>
<style>
body { font-family: Arial, sans-serif; padding: 2rem; }
pre { background: #f4f4f4; padding: 1rem; border-radius: 5px; }
</style>
</head>
<body>
<h1>JSON Sandbox</h1>
<pre id="output"></pre>
<script>
const out = document.getElementById('output');
let result = '';
// Object to JSON
const person = {
name: 'Alice',
age: 25,
skills: ['JavaScript', 'CSS', 'HTML']
};
const json = JSON.stringify(person, null, 2);
result += 'JSON stringified:\n' + json + '\n\n';
// JSON string back to object
const parsed = JSON.parse(json);
result += `Parsed: ${parsed.name}, ${parsed.age}\n`;
result += `Skills: ${parsed.skills.join(', ')}\n\n`;
// API-like response
const apiResponse = `{"users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
]}`;
const data = JSON.parse(apiResponse);
result += 'Users from "API":\n';
data.users.forEach(u => {
result += ` ${u.id}: ${u.name}\n`;
});
out.textContent = result;
</script>
</body>
</html>What’s Next
Now that you understand JSON, use it with async operations and modules:
| Lesson | Description |
|---|---|
| JavaScript Home | Back to the JavaScript hub |
| https://tutorials.dodatech.com/programming-languages/javascript/js-async/ | Async JavaScript — fetch JSON from APIs |
| https://tutorials.dodatech.com/programming-languages/javascript/js-modules/ | Modules & Error Handling |
| https://tutorials.dodatech.com/programming-languages/javascript/js-collections/ | Sets, Maps & Iterables |
| REST API Design | Designing APIs that return JSON |
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
What’s Next
Congratulations on completing this Js Json tutorial! Here’s where to go from here:
- Practice daily — Consistency is more important than long study sessions
- Build a project — Apply what you learned by building something real
- Explore related topics — Check out other tutorials in the same category
- Join the community — Discuss with other learners and share your progress
Remember: every expert was once a beginner. Keep coding!
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro