JSON in JavaScript
JSON (JavaScript Object Notation) is the universal language of data exchange on the web. Every API you call, every config file you read, every database response you handle — it's JSON. Master it once and it pays dividends everywhere.
What is JSON?
JSON stands for JavaScript Object Notation. It is a lightweight, text-based data format that is easy for humans to read and write, and easy for machines to parse and generate. Despite the name, JSON is language-independent — it is used across Python, Java, Go, Ruby, PHP, and virtually every modern language.
JSON was derived from JavaScript object syntax, but it is a
string, not an object. When data travels between a server and a browser, it
travels as text (JSON). JavaScript converts that text into a real object using JSON.parse(), and converts an object back into text using
JSON.stringify().
JSON Syntax Rules
JSON has strict rules — unlike JavaScript object literals, there is no room for shortcuts:
{
"name": "Riya Patel",
"age": 24,
"isActive": true,
"score": null,
"skills": ["HTML", "CSS", "JavaScript"],
"address": {
"city": "Vadodara",
"state": "Gujarat"
}
}
// ❌ Single quotes NOT allowed
{ 'name': 'Alice' }
// ❌ Keys MUST be double-quoted strings
{ name: "Alice" }
// ❌ Trailing commas NOT allowed
{ "name": "Alice", }
// ❌ Comments NOT allowed in JSON
{
// this is a comment — INVALID JSON!
"name": "Alice"
}
// ❌ undefined is NOT a valid JSON value
{ "value": undefined }
// ✅ VALID JSON — all keys double-quoted, no trailing commas
{
"name": "Alice",
"age": 30
}
JSON Data Types
JSON supports exactly six data types. Note that undefined, functions, and Date objects are not valid JSON values:
"hello"
42 or
3.14
true or
false
null
{ }
braces
[ ]
brackets
{
"title": "JavaScript Tutorial", // string
"chapters": 78, // number
"rating": 4.9, // number (float)
"published":true, // boolean
"discount": null, // null
"tags": ["beginner", "web", "JS"], // array
"author": { // object
"name": "K2infocom",
"city": "Vadodara"
}
}
JSON.parse() — String to Object
JSON.parse() takes a JSON
string and converts it into a JavaScript value (usually an object
or array). This is what you do with every API response you receive.
// ── Basic parse ───────────────────────────────────
const jsonStr = '{"name":"Alice","age":28,"active":true}';
const user = JSON.parse(jsonStr);
console.log(user.name); // "Alice"
console.log(user.age); // 28
console.log(user.active); // true
console.log(typeof user); // "object"
// ── Parse an array ────────────────────────────────
const arrStr = '[1, 2, 3, 4, 5]';
const nums = JSON.parse(arrStr);
console.log(nums[2]); // 3
// ── Parse with reviver function ───────────────────
// reviver lets you transform values during parsing
const data = '{"price":100,"tax":18}';
const parsed = JSON.parse(data, (key, value) => {
if (typeof value === 'number') return value * 2;
return value;
});
console.log(parsed); // { price: 200, tax: 36 }
// ── Safe parse with try/catch ─────────────────────
function safeParse(str) {
try {
return JSON.parse(str);
} catch (err) {
console.error("Invalid JSON:", err.message);
return null;
}
}
safeParse('{"name":"Bob"}'); // { name: "Bob" }
safeParse("not valid json"); // null (logs error)
JSON.parse() throws a SyntaxError if the
string is invalid JSON. Always wrap it in try/catch when
dealing with external data you don't control.
JSON.stringify() — Object to String
JSON.stringify() converts a
JavaScript value into a JSON string. You use it when sending
data to a server, saving to localStorage, or logging structured data.
// ── Basic stringify ───────────────────────────────
const user = { name: "Alice", age: 28, active: true };
const json = JSON.stringify(user);
console.log(json);
// '{"name":"Alice","age":28,"active":true}'
console.log(typeof json); // "string"
// ── Pretty-print with indent ──────────────────────
const pretty = JSON.stringify(user, null, 2);
console.log(pretty);
// {
// "name": "Alice",
// "age": 28,
// "active": true
// }
// ── Replacer — pick specific keys ─────────────────
const profile = { name: "Bob", password: "secret", age: 30 };
const safe = JSON.stringify(profile, ["name", "age"]);
console.log(safe); // '{"name":"Bob","age":30}' — password omitted!
// ── Replacer function ─────────────────────────────
const filtered = JSON.stringify(profile, (key, value) => {
if (key === 'password') return undefined; // omit
return value;
});
console.log(filtered); // '{"name":"Bob","age":30}'
// ── What stringify ignores ────────────────────────
const messy = {
name: "Charlie",
fn: () => "hello", // ← functions: omitted
undef: undefined, // ← undefined: omitted
sym: Symbol("id"), // ← symbols: omitted
};
JSON.stringify(messy); // '{"name":"Charlie"}'
2 for human-readable output.Working with Nested JSON
Real-world API responses are rarely flat. You'll regularly encounter deeply nested JSON — objects inside objects, arrays of objects, and mixed structures. Here's how to navigate them confidently:
const jsonStr = `{
"course": "JavaScript",
"instructor": {
"name": "K2infocom",
"location": {
"city": "Vadodara",
"state": "Gujarat"
}
},
"students": [
{ "id": 1, "name": "Riya", "grade": "A" },
{ "id": 2, "name": "Arjun", "grade": "B" },
{ "id": 3, "name": "Priya", "grade": "A" }
],
"prices": [4999, 7999, 11999]
}`;
const data = JSON.parse(jsonStr);
// Access nested object
console.log(data.instructor.name); // "K2infocom"
console.log(data.instructor.location.city); // "Vadodara"
// Access array element
console.log(data.students[0].name); // "Riya"
console.log(data.students[1].grade); // "B"
// Iterate over array of objects
data.students.forEach(s => {
console.log(`${s.name}: ${s.grade}`);
});
// Filter A-grade students
const topStudents = data.students.filter(s => s.grade === "A");
// Optional chaining — safe deep access
console.log(data?.instructor?.location?.pincode); // undefined (no error)
// Deep clone via stringify + parse
const clone = JSON.parse(JSON.stringify(data));
JSON.parse(JSON.stringify(obj)) is the classic trick for a
deep clone — it creates a completely independent copy with no shared
references. The caveat: it strips undefined, functions,
Date objects (converted to strings), and Symbol values. For those, use structuredClone() instead.
Fetching JSON from an API
The most common real-world use of JSON is receiving data from a REST API
using the fetch() function. The response.json() method automatically parses the JSON response
body:
// ── GET request — fetch JSON data ─────────────────
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(response => {
if (!response.ok) throw new Error("Network error");
return response.json(); // parses JSON automatically
})
.then(user => {
console.log(user.name);
console.log(user.email);
})
.catch(err => console.error(err));
// ── async/await version (cleaner) ─────────────────
async function getUser(id) {
try {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const user = await res.json();
return user;
} catch (err) {
console.error("Fetch failed:", err);
}
}
// ── POST request — send JSON to server ────────────
async function createPost(data) {
const res = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data) // object → JSON string
});
const created = await res.json();
console.log("Created:", created);
}
createPost({ title: "Learn JSON", body: "It's easy!", userId: 1 });
JSON vs XML
Before JSON became dominant, XML was the standard for data exchange. Here's why JSON won:
| Feature | JSON | XML |
|---|---|---|
| Readability | Clean, minimal syntax | Verbose tags, harder to read |
| Size | Compact — less bytes | Larger — opening & closing tags |
| Parsing in JS | JSON.parse() — built-in |
DOMParser — more complex |
| Data types | 6 native types | Everything is text |
| Comments | Not supported | Supported |
| Attributes | Not supported | Supported |
| Primary use today | REST APIs, config, storage | Legacy systems, SOAP, RSS, SVG |
/* ── XML (verbose) ─── */
<user>
<name>Alice</name>
<age>28</age>
<skills>
<skill>HTML</skill>
<skill>CSS</skill>
</skills>
</user>
/* ── JSON (compact) ─── */
{
"name": "Alice",
"age": 28,
"skills": ["HTML", "CSS"]
}
JSON with localStorage
localStorage only stores strings. JSON
is the bridge that lets you save objects and arrays to the browser's persistent storage:
// ── Save object to localStorage ───────────────────
const settings = {
theme: "dark",
fontSize: 16,
notifications: true
};
localStorage.setItem("userSettings", JSON.stringify(settings));
// ── Load object from localStorage ────────────────
const raw = localStorage.getItem("userSettings");
const loaded = raw ? JSON.parse(raw) : {};
console.log(loaded.theme); // "dark"
console.log(loaded.fontSize); // 16
// ── Helper functions ──────────────────────────────
const Storage = {
set(key, value) {
localStorage.setItem(key, JSON.stringify(value));
},
get(key, fallback = null) {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : fallback;
} catch { return fallback; }
},
remove(key) { localStorage.removeItem(key); }
};
Storage.set("cart", [{ id: 1, qty: 2 }, { id: 3, qty: 1 }]);
const cart = Storage.get("cart", []);
console.log(cart[0].qty); // 2
Where JSON is Used
JSON is literally everywhere in modern software development:
Try It Yourself
JSON.stringify(data, null, 2) for readable output in console.log() debugging.
What does JSON.parse('{"score": 99}') return?
- JSON (JavaScript Object Notation) is a text-based, language-independent data format used everywhere on the web.
- JSON supports exactly six types: string, number, boolean, null, object, and array.
- Keys must be double-quoted strings — no single quotes, no trailing commas, no comments.
JSON.parse(str)converts a JSON string into a JavaScript object — always wrap intry/catch.JSON.stringify(obj, replacer, indent)converts a JavaScript value into a JSON string; functions,undefined, and symbols are silently omitted.- Use
response.json()afterfetch()to automatically parse API responses. - JSON is the bridge for localStorage — stringify before saving, parse after loading.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.