IS
ISSARAPONG
Developer
🇹🇭 ภาษาไทย

ทำความเข้าใจ JSON

คู่มือฉบับสมบูรณ์เกี่ยวกับ JSON (JavaScript Object Notation) — โครงสร้าง ชนิดข้อมูล การใช้งานใน JavaScript, Python, Go และแนวทางปฏิบัติที่ดีสำหรับนักพัฒนา

Issarapong1 มิถุนายน 25674 นาที

ทำความเข้าใจ JSON

JSON (JavaScript Object Notation) คือรูปแบบการแลกเปลี่ยนข้อมูลที่อ่านได้ง่ายสำหรับทั้งมนุษย์และเครื่องจักร ถูกใช้อย่างแพร่หลายใน API, ไฟล์ Config และการจัดเก็บข้อมูลทั่วทั้งอุตสาหกรรมซอฟต์แวร์

JSON คืออะไร?

JSON เป็นรูปแบบข้อความที่เป็นอิสระจากภาษาโปรแกรม (Language-independent) แต่ใช้ syntax ที่คุ้นเคยจาก JavaScript มาตรฐานนี้ถูกกำหนดใน RFC 8259

เหตุผลที่ JSON ได้รับความนิยม

  • อ่านง่าย — มนุษย์สามารถอ่านและเขียนได้โดยตรง
  • น้ำหนักเบา — ขนาดเล็กกว่า XML มาก
  • รองรับกว้างขวาง — ทุกภาษาโปรแกรมมี parser ในตัว
  • ใช้กับ API — รูปแบบมาตรฐานสำหรับ REST API และ GraphQL

โครงสร้างและชนิดข้อมูล

JSON รองรับชนิดข้อมูล 6 ประเภท:

ชนิดตัวอย่าง
String"สวัสดี", "hello"
Number42, 3.14, -7
Booleantrue, false
Nullnull
Array[1, 2, 3]
Object{"key": "value"}

ตัวอย่าง JSON Object

{
  "id": 1,
  "name": "สมชาย ใจดี",
  "email": "[email protected]",
  "age": 30,
  "isActive": true,
  "score": 9.5,
  "address": null,
  "tags": ["developer", "designer"],
  "profile": {
    "avatar": "https://example.com/avatar.png",
    "bio": "นักพัฒนาซอฟต์แวร์"
  }
}

กฎการเขียน JSON

  • คีย์ต้องเป็น String ที่อยู่ในเครื่องหมายคำพูดคู่ ("key")
  • ไม่อนุญาตให้มี Trailing Comma[1, 2, 3,] ไม่ถูกต้อง
  • ไม่มี Comment — JSON ไม่รองรับ // หรือ /* */
  • String ต้องใช้ " เท่านั้น — ไม่ใช่ '

JSON ที่ถูกต้อง vs ไม่ถูกต้อง

// ✅ ถูกต้อง
{
  "name": "Alice",
  "scores": [10, 20, 30]
}
// ❌ ไม่ถูกต้อง — trailing comma และ comment
{
  "name": "Alice",  // ชื่อผู้ใช้
  "scores": [10, 20, 30,],
}

การใช้งานใน JavaScript

Parse และ Stringify

// แปลง JSON string เป็น JavaScript object
const jsonString = '{"name":"Alice","age":25}';
const user = JSON.parse(jsonString);
console.log(user.name); // Alice

// แปลง JavaScript object เป็น JSON string
const data = { name: "Bob", active: true };
const json = JSON.stringify(data);
console.log(json); // {"name":"Bob","active":true}

// จัดรูปแบบให้อ่านง่าย (pretty print)
const pretty = JSON.stringify(data, null, 2);
console.log(pretty);
// {
//   "name": "Bob",
//   "active": true
// }

การกรองและแปลงค่า (Replacer/Reviver)

// Replacer: กรองฟิลด์ที่ต้องการ
const user = { name: "Alice", password: "secret", age: 25 };
const safe = JSON.stringify(user, ["name", "age"]);
console.log(safe); // {"name":"Alice","age":25}

// Reviver: แปลงค่าขณะ parse
const json = '{"createdAt":"2024-01-15T10:00:00Z"}';
const obj = JSON.parse(json, (key, value) => {
  if (key === "createdAt") return new Date(value);
  return value;
});
console.log(obj.createdAt instanceof Date); // true

การดึงข้อมูลจาก API

// Fetch JSON จาก API
async function getUser(id) {
  const response = await fetch(`https://api.example.com/users/${id}`);
  if (!response.ok) throw new Error(`HTTP error: ${response.status}`);
  const user = await response.json(); // แปลง response เป็น JSON อัตโนมัติ
  return user;
}

การใช้งานใน Python

import json

# แปลง JSON string เป็น Python dict
json_str = '{"name": "Alice", "age": 25}'
data = json.loads(json_str)
print(data["name"])  # Alice

# แปลง Python dict เป็น JSON string
user = {"name": "Bob", "active": True, "score": None}
json_out = json.dumps(user)
print(json_out)  # {"name": "Bob", "active": true, "score": null}

# อ่านไฟล์ JSON
with open("config.json", "r", encoding="utf-8") as f:
    config = json.load(f)

# เขียนไฟล์ JSON
with open("output.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

การใช้งานใน Go

package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    Name  string `json:"name"`
    Email string `json:"email"`
    Age   int    `json:"age"`
}

func main() {
    // Marshal: Go struct → JSON
    user := User{Name: "Alice", Email: "[email protected]", Age: 25}
    data, _ := json.Marshal(user)
    fmt.Println(string(data))
    // {"name":"Alice","email":"[email protected]","age":25}

    // Unmarshal: JSON → Go struct
    jsonStr := `{"name":"Bob","email":"[email protected]","age":30}`
    var result User
    json.Unmarshal([]byte(jsonStr), &result)
    fmt.Println(result.Name) // Bob
}

JSON Schema

JSON Schema คือมาตรฐานสำหรับอธิบายและตรวจสอบโครงสร้างของ JSON

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "name": {
      "type": "string",
      "minLength": 1
    },
    "age": {
      "type": "integer",
      "minimum": 0,
      "maximum": 150
    },
    "email": {
      "type": "string",
      "format": "email"
    }
  },
  "required": ["name", "email"]
}

รูปแบบที่เกี่ยวข้อง

รูปแบบคำอธิบาย
JSON5JSON ที่รองรับ comment และ trailing comma
JSONCJSON with Comments (ใช้ใน VS Code config)
NDJSONNewline Delimited JSON สำหรับ streaming
JSON Linesคล้าย NDJSON ใช้สำหรับ log และ data pipeline

แนวทางปฏิบัติที่ดี

  • ใช้ camelCase สำหรับคีย์ — เช่น firstName ไม่ใช่ first_name (สำหรับ JavaScript)
  • อย่าเก็บข้อมูลลับ — JSON ถอดรหัสได้ง่าย ไม่เหมาะกับ password หรือ secret
  • Validate ก่อนใช้ — ตรวจสอบ JSON ที่รับมาจากภายนอกด้วย JSON Schema
  • จัดการ ErrorJSON.parse() จะ throw หากข้อมูลผิดรูปแบบ ควร try-catch เสมอ
// ✅ แนวทางที่ดี
function safeParse(str) {
  try {
    return JSON.parse(str);
  } catch {
    return null;
  }
}

ลองใช้งานได้เลย

ใช้ เครื่องมือ JWT Decoder ของเราเพื่อดู JSON Payload ภายใน JWT Token หรือลองทดสอบ JSON กับ API Client

เครื่องมือที่เกี่ยวข้อง

  • JWT Decoder — ถอดรหัสและตรวจสอบ JWT ที่มี JSON payload
  • Base64 Encoder — JSON มักถูก Base64 encode ในหลายบริบท
  • URL Encoder/Decoder — เข้ารหัส JSON สำหรับใช้ใน URL