Ch 66 / 78
Chapter 66 Beginner 7 min read JavaScript

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 you'll learn
What JSON is and why it's the web's data format
All six JSON data types with examples
JSON.parse() — string → JavaScript object
JSON.stringify() — object → JSON string
Working with nested JSON and arrays
Fetching & handling real JSON APIs

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().

Text Format
JSON is always a string — it travels over networks as plain text and is parsed on arrival.
Language Agnostic
Any language can read and write JSON — making it the universal glue between systems.
Lightweight
Less verbose than XML. Only curly braces, square brackets, quotes, colons, and commas.
Structured
Supports nested objects and arrays — ideal for representing hierarchical data.

JSON Syntax Rules

JSON has strict rules — unlike JavaScript object literals, there is no room for shortcuts:

JSON — Valid Syntax
{
  "name":    "Riya Patel",
  "age":     24,
  "isActive": true,
  "score":   null,
  "skills":  ["HTML", "CSS", "JavaScript"],
  "address": {
    "city":  "Vadodara",
    "state": "Gujarat"
  }
}
JSON — Common Mistakes
// ❌ 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:

string Text in double quotes — "hello"
number Integer or float — 42 or 3.14
boolean Lowercase only — true or false
null Represents no value — null
object Key-value pairs in { } braces
array Ordered list in [ ] brackets
JSON — All Six Types
{
  "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.

JS — JSON.parse()
// ── 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)
Common Mistake
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.

JS — JSON.stringify()
// ── 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"}'
value (required)
The JavaScript value to convert — object, array, string, number, boolean, or null.
replacer (optional)
An array of keys to include, or a function to transform/omit values during serialisation.
space (optional)
Number of spaces (or a string) for indentation. Use 2 for human-readable output.
⚡
Free Resource
Download our JavaScript Cheat Sheet
JSON methods, Fetch API patterns — all on one page.
Get Sheet

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:

JS — Navigating Nested JSON
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));
Pro Tip
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:

JS — Fetch API with JSON
// ── 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
JSON vs XML — Same Data
/* ── 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"]
}
Advertisement

JSON with localStorage

localStorage only stores strings. JSON is the bridge that lets you save objects and arrays to the browser's persistent storage:

JS — Save & Load Objects with localStorage
// ── 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:

REST APIs
NoSQL Databases
Config Files
localStorage
WebSockets
GraphQL Responses
package.json / tsconfig
Analytics Events

Try It Yourself

Live Editor
✎ Editor
👁 Preview
Pro Tip
Use JSONLint.com or your browser's DevTools Network tab to validate and inspect JSON responses from real APIs. Pretty-print with JSON.stringify(data, null, 2) for readable output in console.log() debugging.
Quick Check — Chapter 66

What does JSON.parse('{"score": 99}') return?

Chapter Summary
  • 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 in try/catch.
  • JSON.stringify(obj, replacer, indent) converts a JavaScript value into a JSON string; functions, undefined, and symbols are silently omitted.
  • Use response.json() after fetch() to automatically parse API responses.
  • JSON is the bridge for localStorage — stringify before saving, parse after loading.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel