JSON là gì — file 'mặt mũi' của mọi API + cấu hình hiện đại
JSON (JavaScript Object Notation) là format dữ liệu phổ biến nhất 2026 — dùng cho mọi API, file cấu hình (package.json, tsconfig), và lưu data. Đọc/viết được JSON = đọc được response API, debug được config, hiểu được code dev gửi. Tiếng Anh dễ học nhất của ngành tech.
Mục lục bài viết(27)

Ví dụ JSON code với các thành phần cơ bản: key-value pair ("name": "value"), array [item1, item2], nested object { "addr": { "city": "HN" } }. Indent 2 hoặc 4 space là convention phổ biến. JSON là format trao đổi data phổ biến nhất 2026 — mọi REST API, mọi config file modern, mọi NoSQL DB đều dùng JSON. Nguồn: Wikimedia Commons (CC BY-SA 4.0).
Hiểu đơn giản nhất
JSON là cách viết data mà cả người + máy đọc được.
Tưởng tượng bạn có danh thiếp của một người:
Nguyễn Văn A
Founder vietcodex.com
Điện thoại: 0987654321
Email: [email protected]
Địa chỉ:
Quận 1, HCM
Việt Nam
Kỹ năng: React, Next.js, Postgres
Chuyển sang JSON — chỉ thay cách viết, không thay nội dung:
{
"name": "Nguyễn Văn A",
"title": "Founder vietcodex.com",
"phone": "0987654321",
"email": "[email protected]",
"address": {
"district": "Quận 1",
"city": "HCM",
"country": "Việt Nam"
},
"skills": ["React", "Next.js", "Postgres"]
}JSON viết tắt từ JavaScript Object Notation — được phát minh năm 2001 bởi Douglas Crockford. Hiện là format trao đổi data phổ biến nhất internet.
6 kiểu data trong JSON
| Type | Ví dụ |
|---|---|
| String | "Nguyễn Văn A" (luôn double quote) |
| Number | 42, 3.14, -99 |
| Boolean | true, false |
| Null | null (không có value) |
| Array | ["a", "b", "c"] (list) |
| Object | { "key": "value" } (dictionary) |
Mọi cấu trúc phức tạp đều ghép từ 6 kiểu này.
Tại sao bạn cần biết
- Đọc được response từ mọi API. Stripe, Zalo, OpenAI, Casso — tất cả trả JSON. Hiểu structure = debug được.
- Đọc được file config dev gửi.
package.json(Node),tsconfig.json,next.config.json,manifest.json— đều JSON. - Hiểu data API document. Stripe docs có ví dụ JSON cho mọi endpoint. Bạn cần know shape data đáp ứng yêu cầu integration.
- Build no-code workflow chính xác. Zapier, Make, n8n đều pass JSON giữa các step. Map field sai = workflow vỡ.
- Debug webhook payload. Casso/VNPay webhook gửi JSON body. Bạn cần đọc được để biết "tx id nào, amount bao nhiêu".
- JSON-LD = SEO Rich Snippet. Schema FAQPage, Article, Product trong JSON-LD = Google hiểu nội dung trang sâu hơn.
Cú pháp JSON — 5 quy tắc
Quy tắc 1: Key PHẢI double quote
✅ { "name": "Vietcodex" }
❌ { name: "Vietcodex" } ← thiếu quote
❌ { 'name': "Vietcodex" } ← single quote không chấp nhậnJavaScript Object cho phép { name: ... } (no quote), JSON KHÔNG.
Quy tắc 2: String PHẢI double quote
✅ "Việt Nam"
❌ 'Việt Nam' ← single quote saiQuy tắc 3: Comma ngăn cách, KHÔNG có trailing comma
✅ { "a": 1, "b": 2 }
❌ { "a": 1, "b": 2, } ← trailing comma cuốiExcel-savvy thường gõ trailing comma — JSON sẽ syntax error. JSON5 cho phép, JSON spec KHÔNG.
Quy tắc 4: Không comment
❌ {
// Đây là comment - SAI
"name": "value"
}
✅ {
"_comment": "Đây là workaround dùng key tên _comment",
"name": "value"
}Quy tắc 5: Nested vô tận
{
"company": {
"name": "Vietcodex",
"founders": [
{
"name": "A",
"skills": ["React", "Next.js"],
"address": {
"city": "HCM",
"geo": { "lat": 10.77, "lng": 106.7 }
}
},
{ "name": "B", "skills": [] }
]
}
}Bạn có thể nest unlimited, nhưng > 5 tầng = khó đọc + maintain. Flatten cấu trúc khi có thể.
JSON trong API — ví dụ thực
REST API GET response
GET https://api.shopee.vn/products/123
{
"id": 123,
"name": "Áo thun nam basic",
"price": 199000,
"currency": "VND",
"in_stock": true,
"stock_count": 42,
"category": {
"id": 5,
"slug": "ao-thun-nam",
"name": "Áo thun nam"
},
"images": [
"https://cf.shopee.vn/products/123/main.jpg",
"https://cf.shopee.vn/products/123/back.jpg"
],
"ratings": {
"average": 4.5,
"count": 89,
"distribution": {
"5": 50,
"4": 25,
"3": 8,
"2": 4,
"1": 2
}
},
"created_at": "2025-01-15T10:30:00Z"
}REST API POST body
POST https://api.casso.vn/transactions
{
"id": 123456,
"tid": "FT2026000123456",
"description": "VC2026000001",
"amount": 800000,
"when": "2026-05-22T10:30:00Z",
"bank_sub_acc_id": "vcb-9999",
"sub_acc_id": "9999",
"virtual_account": "",
"virtual_account_name": "",
"corresponsive_name": "NGUYEN VAN A",
"corresponsive_account": "1023456789",
"corresponsive_bank_id": "970436",
"corresponsive_bank_name": "Vietcombank"
}Error response
{
"success": false,
"error": {
"code": "INVALID_INPUT",
"message": "Email is required",
"details": {
"field": "email",
"received": null
}
}
}JSON trong config file
package.json (Node.js project)
{
"name": "vietcodex-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "node scripts/build-wiki-index.mjs && next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "16.2.6",
"react": "^19.0.0",
"better-auth": "^1.6.10",
"drizzle-orm": "^0.45.2"
},
"devDependencies": {
"typescript": "^5.3.0",
"@types/node": "^20.0.0"
}
}tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"paths": {
"@/*": ["./*"]
}
},
"include": ["**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}.vscode/settings.json
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"files.exclude": {
"**/.next": true,
"**/node_modules": true
}
}JSON-LD — JSON cho SEO
JSON-LD nhúng trong HTML để Google hiểu nội dung:
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@graph": [
{
"@type": "Article",
"headline": "Cookies, Session, Token — 3 cách web nhớ bạn",
"datePublished": "2026-05-22",
"author": {
"@type": "Organization",
"name": "VietCodex"
}
},
{
"@type": "BreadcrumbList",
"itemListElement": [
{ "@type": "ListItem", "position": 1, "name": "Wiki", "item": "https://wiki.vietcodex.com" },
{ "@type": "ListItem", "position": 2, "name": "Cơ bản", "item": "https://wiki.vietcodex.com/co-ban" }
]
},
{
"@type": "FAQPage",
"mainEntity": [
{
"@type": "Question",
"name": "Cookies có nguy hiểm không?",
"acceptedAnswer": { "@type": "Answer", "text": "..." }
}
]
}
]
}
</script>Google parse JSON-LD → hiện Rich Snippet:
- FAQ accordion trong SERP
- Breadcrumb thay vì URL
- Article date + author
Tăng CTR 20-30%.
Parse + Stringify trong JavaScript
Parse — JSON string → JS Object
const jsonStr = '{"name":"A","age":25}';
const obj = JSON.parse(jsonStr);
console.log(obj.name); // "A"
console.log(obj.age); // 25Stringify — JS Object → JSON string
const obj = { name: "A", age: 25, skills: ["React"] };
const jsonStr = JSON.stringify(obj);
// '{"name":"A","age":25,"skills":["React"]}'
// Pretty print với indent 2 space:
const pretty = JSON.stringify(obj, null, 2);
// {
// "name": "A",
// "age": 25,
// "skills": ["React"]
// }Common pitfalls
// 1. Date không trong JSON spec
const obj = { date: new Date() };
const str = JSON.stringify(obj);
// '{"date":"2026-05-22T10:30:00.000Z"}'
const back = JSON.parse(str);
back.date instanceof Date; // false! Là string thường
// Cần re-parse manual:
back.date = new Date(back.date);
// 2. undefined biến mất
JSON.stringify({ a: undefined, b: null });
// '{"b":null}' ← a không tồn tại
// 3. Function biến mất
JSON.stringify({ fn: () => 1 });
// '{}'
// 4. Circular reference throw
const a = { name: "A" };
a.self = a;
JSON.stringify(a); // TypeError: Converting circular structureTools làm việc với JSON
| Tool | Use case |
|---|---|
| jq (CLI) | Parse + transform JSON từ shell: `curl ... |
| JSONLint (web) | Validate JSON syntax, hint lỗi |
| JSON Editor Online | Edit JSON với tree view |
| Postman / Insomnia / Bruno | Test API + view JSON response đẹp |
| DevTools Network tab | Xem JSON response của mọi request |
| VSCode JSON Tools extension | Format, validate, fold trong editor |
| Zod / Yup / Joi (npm) | Validate JSON schema trong code TS |
Ví dụ thực tế: wiki.vietcodex.com search index
File public/wiki-search-index.json được generate mỗi build:
[
{
"slug": "co-ban/cookies-session-token",
"title": "Cookies, Session, Token — 3 cách web nhớ bạn",
"description": "HTTP vốn không có trí nhớ...",
"category": "co-ban",
"categoryLabel": "Cơ bản",
"tags": ["cookies", "session", "token", "jwt"],
"headings": ["Hiểu đơn giản nhất", "Tại sao bạn cần biết", ...],
"body": "Hiểu đơn giản nhất Web hoạt động trên HTTP..."
},
{
"slug": "co-ban/https-ssl-tls",
"title": "HTTPS, SSL, TLS...",
...
}
]Frontend fetch file 213KB này, dùng Fuse.js search local — không cần backend.
Cái gì có thể sai
| Vấn đề | Triệu chứng | Cách fix |
|---|---|---|
| "Unexpected token" khi parse | Trailing comma hoặc single quote | Validate qua JSONLint.com trước |
| Date sau parse thành string | JSON không có Date type | Reviver function trong JSON.parse(s, reviver) |
| API response không match TS type | Schema không validate | Dùng Zod để parse + validate |
| Prototype pollution attack | Input có __proto__ | Validate keys trước khi merge, dùng Object.create(null) |
| File JSON 100MB ăn hết RAM | Load toàn file | Stream parse với stream-json hoặc convert JSONL |
| BigInt overflow (Twitter ID) | Number JS chỉ 2^53 | Dùng string thay vì number cho ID lớn |
| Unicode escape sai | é vs é | UTF-8 encoding đầy đủ, đừng escape ASCII-only |
Tóm tắt 1 dòng
JSON = format trao đổi data phổ biến nhất 2026 (API, config, NoSQL DB, log, schema SEO). 6 kiểu: string/number/boolean/null/array/object. Key + string PHẢI double quote, không trailing comma, không comment.
JSON.parse()+JSON.stringify()built-in mọi browser. JSON-LD trong HTML = Google hiểu nội dung → Rich Snippet SERP. Đọc JSON = đọc được response mọi API + debug config dev gửi.
Đọc tiếp
- API là gì? Tại sao mọi app, mọi web hiện đại đều cần — JSON là format chuẩn cho mọi REST API
- Webhook là gì — cách Casso, Stripe, Zalo "gõ cửa" web của bạn — webhook body 99% là JSON
- Database là gì? So sánh dễ hiểu với Excel — NoSQL (MongoDB) lưu document JSON, SQL có cột
jsonb(Postgres) - Framework là gì? React, Vue, Next.js — bộ Lego cho lập trình viên — package.json là JSON, config framework là JSON