หัวข้อสำคัญของ Go

Go JSON: Marshal and Unmarshal

Turn structs into JSON and JSON into structs, with struct tags to choose the field names.

  • ระดับกลาง
  • อ่าน 3 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • json.Marshal
  • json.Unmarshal
  • Struct tags and omitempty
Round trip
  1. 1Product{...}a struct
  2. 2json.Marshal{"name":"Go Book",...}
  3. 3json.Unmarshalback to a struct

Structs to JSON and back

The encoding/json package converts Go values to JSON text and JSON text back to Go values. Struct tags choose the names used in the JSON.

Marshal turns the struct into JSON bytes, using the names from the json tags. Unmarshal fills a struct from JSON and needs a pointer so it can change the value. omitempty leaves a field out when it is empty, and a missing field keeps its zero value.

ประเด็นสำคัญ

  1. Tags choose the names used in JSON.
  2. Unmarshal needs a pointer.
  3. omitempty leaves out empty fields.

ตัวอย่าง Go ที่รันได้

Go
รันโค้ด →
main.go
package main

import (
	"encoding/json"
	"fmt"
)

type Product struct {
	Name  string   `json:"name"`
	Price float64  `json:"price"`
	Tags  []string `json:"tags,omitempty"`
}

func main() {
	book := Product{Name: "Go Book", Price: 12.5, Tags: []string{"go", "learning"}}
	data, err := json.Marshal(book)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println(string(data))

	var parsed Product
	input := `{"name":"Pen","price":1.25}`
	if err := json.Unmarshal([]byte(input), &parsed); err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("%s costs %.2f, tags: %d\n", parsed.Name, parsed.Price, len(parsed.Tags))
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
{"name":"Go Book","price":12.5,"tags":["go","learning"]}
Pen costs 1.25, tags: 0

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Sorting Slices →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด