🏠 Home / Hub

📡 JSON & AJAX Lesson 01 — JSON Basics

← Back to JSON Menu  |  🏠 Hub

1. JSON ဆိုတာ ဘာလဲ

JSON = JavaScript Object Notation
Data ကို text format နဲ့ store/transfer လုပ်ဖို့ standard — lightweight, human-readable

🌐 API response format အများဆုံး
📦 Config files (package.json, tsconfig.json)
💾 Database storage (MongoDB, Firestore)
🔗 Frontend ↔ Backend data exchange
// JSON example — user data
{
  "name": "Ko Ko",
  "age": 25,
  "active": true,
  "score": null,
  "skills": ["HTML", "CSS", "JavaScript"],
  "address": {
    "city": "Yangon",
    "country": "Myanmar"
  }
}

2. JSON Data Types

TypeExampleNote
String"Hello World"Double quotes ပဲ သုံး (single quotes ❌)
Number25, 3.14, -10Integer & float both OK
Booleantrue, falselowercase only
nullnullempty value
Array["a", "b", 1, true]Mixed types OK
Object{"key": "value"}Nested objects OK
// ❌ Invalid JSON (common mistakes)
{
  name: "Ko Ko",          // key ကို quotes မထည့်ဘူး
  'age': 25,              // single quotes သုံး
  active: True,           // Boolean uppercase
  note: undefined,        // undefined မရှိဘူး JSON မှာ
  fn: function() {}       // functions ✗
}

// ✅ Valid JSON
{
  "name": "Ko Ko",
  "age": 25,
  "active": true,
  "note": null
}

3. JSON.parse() — String → Object

// API response / localStorage data = JSON string ဖြစ်တဲ့အတွက် parse လုပ်ရ
const jsonString = '{"name":"Ko Ko","age":25,"skills":["HTML","CSS"]}';

const user = JSON.parse(jsonString);

console.log(user.name);        // "Ko Ko"
console.log(user.age);         // 25
console.log(user.skills[0]);   // "HTML"
console.log(typeof user);      // "object"

// Nested object
const data = JSON.parse('{"user":{"name":"Ma Ma","role":"admin"}}');
console.log(data.user.name);   // "Ma Ma"
console.log(data.user.role);   // "admin"

// Parse error handling
try {
  const bad = JSON.parse("not valid json");
} catch (e) {
  console.error("Parse error:", e.message);
}

4. JSON.stringify() — Object → String

const user = {
  name: "Ko Ko",
  age: 25,
  skills: ["HTML", "CSS"],
  password: "secret123"  // sensitive data ပါနေ
};

// Basic stringify
const jsonStr = JSON.stringify(user);
// '{"name":"Ko Ko","age":25,"skills":["HTML","CSS"],"password":"secret123"}'

// Pretty print (indent: 2 spaces)
const pretty = JSON.stringify(user, null, 2);
/*
{
  "name": "Ko Ko",
  "age": 25,
  "skills": ["HTML", "CSS"],
  "password": "secret123"
}
*/

// Replacer — filter keys
const safe = JSON.stringify(user, ["name", "age", "skills"]);
// '{"name":"Ko Ko","age":25,"skills":["HTML","CSS"]}'
// password excluded!

// Common uses
localStorage.setItem("user", JSON.stringify(user));  // save to storage
const stored = JSON.parse(localStorage.getItem("user"));  // read back
💡 JSON.parse → string to object | JSON.stringify → object to string

5. Nested JSON — Real API Shape

// Real API response example (GitHub-like)
const response = {
  "status": "success",
  "data": {
    "users": [
      {
        "id": 1,
        "name": "Ko Ko",
        "email": "ko@example.com",
        "role": "admin",
        "profile": {
          "avatar": "https://example.com/ko.jpg",
          "bio": "Web developer"
        },
        "tags": ["frontend", "vue"]
      },
      {
        "id": 2,
        "name": "Ma Ma",
        "email": "ma@example.com",
        "role": "editor",
        "profile": {
          "avatar": null,
          "bio": "Content creator"
        },
        "tags": ["design"]
      }
    ],
    "total": 2,
    "page": 1
  }
};

// Access nested data
console.log(response.data.users[0].name);          // "Ko Ko"
console.log(response.data.users[1].profile.bio);   // "Content creator"
console.log(response.data.users[0].tags[1]);       // "vue"

// Loop through users
response.data.users.forEach(user => {
  console.log(`${user.id}: ${user.name} (${user.role})`);
});

← JSON Menu  |  Next: JSON 02 → Fetch GET →

📌 Study Checklist