Trong JavaScript, **JSON Object** thực chất là **Plain Object** (object literal) - có thể serialize thành JSON string bằng JSON.stringify().
Khác với JSON string (chuỗi), JS Object là cấu trúc dữ liệu trong bộ nhớ.
Ví dụ minh họa
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tạo JSON Object JS</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
.sample { font-size: 16px; font-weight: 500; margin: 10px 0; color: #333; background: #f5f5f5; padding: 10px; }
.result { font-size: 18px; font-weight: 500; margin: 10px 0; color: green; }
button { padding: 8px 16px; cursor: pointer; }
</style>
</head>
<body>
<h1>Tạo JSON Object trong JavaScript</h1>
<div class="sample" id="sample"></div>
<div class="result" id="result">JSON OBJECT <br></div>
<button class="Btn" id="btn">NHẤN VÀO ĐÂY</button>
<h3> Nhấn nút để tạo JSON object và hiển thị </h3>
<script>
const resEle = document.querySelector("#result");
const sampleEle = document.querySelector("#sample");
// Tạo object (gọi là JSON object)
const obj = {
firstName: 'Rohan',
lastName: 'Sharma',
age: 14,
isStudent: true,
address: {
city: 'Hanoi',
country: 'Vietnam'
},
hobbies: ['coding', 'reading', 'gaming']
};
sampleEle.innerHTML = JSON.stringify(obj, null, 2);
document.querySelector("#btn").addEventListener("click", () => {
resEle.innerHTML = "JSON OBJECT:
";
// Duyệt object
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key];
resEle.innerHTML += `Key = ${key} : Value = ${JSON.stringify(value)}
`;
}
}
// Demo stringify
resEle.innerHTML += `
--- JSON.stringify() ---
`;
resEle.innerHTML += `Compact: ${JSON.stringify(obj)}
`;
resEle.innerHTML += `Pretty: ${JSON.stringify(obj, null, 2)}`;
});
</script>
</body>
</html>
Kết quả
Hiển thị object pretty-printed. Nhấn nút → Liệt kê key-value, demo JSON.stringify().
Tạo Object - Các cách:
| Cách | Cú pháp | Ghi chú |
|---|---|---|
| Object Literal | { key: value } | Phổ biến nhất, ngắn gọn |
| Constructor | new Object() | Verbose, ít dùng |
| Object.create() | Object.create(proto, props) | Set prototype trực tiếp |
| Class | class User {} + new User() | OOP, tái sử dụng |
| Factory Function | function createUser() { return {...} } | Flexible, closure |
| JSON.parse() | JSON.parse(jsonString) | Từ string (API response) |
JSON Object Rules (Để JSON.stringify() hoạt động):
- Key phải là string (tự động convert:
{1: "a"}→{"1": "a"}) - Value: string, number, boolean, null, array, object (nested)
- KHÔNG hỗ trợ:
undefined,Function,Symbol,BigInt,Date(→ string), circular ref
Deep Clone với JSON (Cách nhanh nhưng có hạn chế):
const original = { a: 1, b: { c: 2 }, arr: [1,2,3] };
const clone = JSON.parse(JSON.stringify(original));
// ⚠️ Mất: Function, undefined, Symbol, Date→string, Circular ref, Prototype chain
Modern Alternative: structuredClone() (ES2022)
const clone = structuredClone(original);
// Hỗ trợ: Date, RegExp, Map, Set, ArrayBuffer, TypedArray, Circular ref!
// Không hỗ trợ: Function, DOM nodes, Symbol (as key)