encoding/json
最後更新
encoding/json 負責在 Go 的值與 JSON 文字之間互相轉換,是寫 API、讀設定檔最常用的套件。這個套件做什麼
JSON 是目前最常見的資料交換格式:HTTP API 的請求與回應、設定檔、訊息佇列幾乎都用它。
encoding/json 提供兩個方向的轉換:- 編碼(encode,又叫 marshal):把 Go 的結構體、切片、映射轉成 JSON 位元組
- 解碼(decode,又叫 unmarshal):把 JSON 位元組填回 Go 的值
套件有兩組用法,差別在資料從哪裡來:
| 用法 | 函式 | 適合情境 |
|---|---|---|
| 一次處理整份資料 | Marshal、Unmarshal | 資料已經在記憶體裡的 []byte |
| 串流(stream) | NewEncoder、NewDecoder | 直接讀寫 io.Reader/io.Writer,例如 HTTP body、檔案、一行一筆的 log |
結構體欄位與 JSON 鍵的對應用 struct tag 控制,概念說明見結構體與 JSON。只有首字母大寫的匯出欄位會被處理。要處理 XML 改用 encoding/xml。
匯入
- import "encoding/json"
常用 API
json.Marshal
把任何 Go 值轉成 JSON,回傳
[]byte。結構體依欄位宣告順序輸出;映射(map)的鍵會先排序再輸出,所以結果固定。簽名:
- func Marshal(v any) ([]byte, error)
範例:
- package main
- import (
- "encoding/json"
- "fmt"
- )
- type Product struct {
- ID int
- Name string
- Price float64
- Tags []string
- }
- func main() {
- p := Product{ID: 1, Name: "鍵盤", Price: 1290.5, Tags: []string{"3C", "周邊"}}
- data, err := json.Marshal(p)
- if err != nil {
- fmt.Println("error:", err)
- return
- }
- fmt.Println(string(data))
- m := map[string]int{"z": 26, "a": 1, "m": 13}
- data, _ = json.Marshal(m)
- fmt.Println(string(data))
- }
輸出:
- {"ID":1,"Name":"鍵盤","Price":1290.5,"Tags":["3C","周邊"]}
- {"a":1,"m":13,"z":26}
注意:channel、函式、複數以及
math.Inf、NaN 無法表示成 JSON,Marshal 會回傳錯誤。[]byte 會被編成 base64 字串,而不是數字陣列。json.MarshalIndent
和
Marshal 一樣,但輸出加上換行與縮排,方便人閱讀,常用在除錯或寫設定檔。prefix 是每行開頭的字串,indent 是每層縮排。簽名:
- func MarshalIndent(v any, prefix, indent string) ([]byte, error)
範例:
- package main
- import (
- "encoding/json"
- "fmt"
- )
- type Config struct {
- Host string
- Port int
- Debug bool
- }
- func main() {
- c := Config{Host: "localhost", Port: 8080, Debug: true}
- data, err := json.MarshalIndent(c, "", " ")
- if err != nil {
- fmt.Println("error:", err)
- return
- }
- fmt.Println(string(data))
- }
輸出:
- {
- "Host": "localhost",
- "Port": 8080,
- "Debug": true
- }
json.Unmarshal
把 JSON 位元組解析後填進
v 指向的值。v 必須是指標,否則套件沒辦法改到你的變數。鍵名比對不分大小寫,JSON 裡多出來的鍵會被忽略,缺少的欄位保持零值。簽名:
- func Unmarshal(data []byte, v any) error
範例:
- package main
- import (
- "encoding/json"
- "fmt"
- )
- type User struct {
- Name string
- Age int
- Email string
- }
- func main() {
- input := []byte(`{"name":"Alice","age":30,"role":"admin"}`)
- var u User
- if err := json.Unmarshal(input, &u); err != nil {
- fmt.Println("error:", err)
- return
- }
- fmt.Printf("%+v\n", u)
- err := json.Unmarshal([]byte(`{"age":"thirty"}`), &u)
- fmt.Println(err)
- }
輸出:
- {Name:Alice Age:30 Email:}
- json: cannot unmarshal string into Go struct field User.Age of type int
注意:傳入非指標或 nil 指標會回傳
*json.InvalidUnmarshalError;型別對不上(字串填進 int)回傳 *json.UnmarshalTypeError;JSON 語法錯誤回傳 *json.SyntaxError。可以用 errors.As 判斷是哪一種。解碼到 any 與 map
不知道資料結構時,可以解碼到
any 或 map[string]any。對應規則是:物件 → map[string]any、陣列 → []any、字串 → string、布林 → bool、數字 → float64、null → nil。取值時要用型別斷言。範例:
- package main
- import (
- "encoding/json"
- "fmt"
- )
- func main() {
- input := []byte(`{"name":"Bob","score":95,"tags":["go","json"],"admin":false}`)
- var m map[string]any
- if err := json.Unmarshal(input, &m); err != nil {
- fmt.Println("error:", err)
- return
- }
- name := m["name"].(string)
- score := m["score"].(float64)
- tags := m["tags"].([]any)
- fmt.Println(name, score, len(tags), tags[0])
- fmt.Printf("%T %T\n", m["score"], m["admin"])
- }
輸出:
- Bob 95 2 go
- float64 bool
注意:數字一律變成
float64,超過 2^53 的大整數(例如雪花 ID)會失去精度。需要保留原始數字時,用 Decoder.UseNumber 讓數字解成 json.Number(字串型別,可再呼叫 Int64() 轉換)。struct tag:改名、omitempty、omitzero
struct tag 是寫在欄位後面的字串,用來告訴
encoding/json 要怎麼處理這個欄位。格式是 json:"名稱,選項":| 寫法 | 效果 |
|---|---|
json:"user_name" | JSON 鍵改名為 user_name |
json:"-" | 這個欄位永遠不輸出也不讀取 |
json:",omitempty" | 值是 false、0、nil 指標、nil 介面、空字串、長度 0 的陣列/切片/映射時省略 |
json:",omitzero" | 值是該型別的零值時省略;型別有 IsZero() bool 方法時改用它判斷(Go 1.24 起) |
json:",string" | 數字或布林以字串形式輸出,例如 "42" |
omitempty 對結構體無效:空結構體 time.Time{} 還是會輸出 "0001-01-01T00:00:00Z"。Go 1.24 起加入的 omitzero 解決這個問題,它看的是「零值」而不是「空」,而且會呼叫 time.Time 的 IsZero 方法。兩者可以同時寫,任一成立就省略。範例:
- package main
- import (
- "encoding/json"
- "fmt"
- "time"
- )
- type Event struct {
- ID int `json:"id"`
- Title string `json:"title"`
- Note string `json:"note,omitempty"`
- Secret string `json:"-"`
- Count int64 `json:"count,string"`
- EmptyAt time.Time `json:"empty_at,omitempty"`
- ZeroAt time.Time `json:"zero_at,omitzero"`
- Labels []string `json:"labels,omitempty"`
- Settings []string `json:"settings,omitzero"`
- }
- func main() {
- e := Event{
- ID: 7,
- Title: "發表會",
- Secret: "hidden",
- Count: 42,
- Settings: []string{},
- }
- data, _ := json.MarshalIndent(e, "", " ")
- fmt.Println(string(data))
- }
輸出:
- {
- "id": 7,
- "title": "發表會",
- "count": "42",
- "empty_at": "0001-01-01T00:00:00Z",
- "settings": []
- }
從輸出可以看到兩個差別:
empty_at 用 omitempty 擋不掉零值時間,zero_at 用 omitzero 成功省略;settings 是長度 0 但不是 nil 的切片,omitzero 只省略 nil 切片,所以仍輸出 [],若想連空切片一起省略就用 omitempty。標籤如何用反射讀取見讀取結構體標籤。json.NewEncoder
Encoder 把值直接寫進 io.Writer,例如 os.Stdout、檔案或 http.ResponseWriter,不必先產生 []byte。每次呼叫 Encode 會在結尾加一個換行。SetIndent 設定縮排,SetEscapeHTML(false) 可以讓 <、>、& 不被轉成 < 之類的跳脫序列。簽名:
- func NewEncoder(w io.Writer) *Encoder
- func (enc *Encoder) Encode(v any) error
- func (enc *Encoder) SetIndent(prefix, indent string)
- func (enc *Encoder) SetEscapeHTML(on bool)
範例:
- package main
- import (
- "encoding/json"
- "fmt"
- "os"
- )
- type Msg struct {
- From string `json:"from"`
- Text string `json:"text"`
- }
- func main() {
- enc := json.NewEncoder(os.Stdout)
- enc.Encode(Msg{From: "a", Text: "x < y && y > z"})
- enc.SetEscapeHTML(false)
- enc.Encode(Msg{From: "b", Text: "x < y && y > z"})
- enc.SetIndent("", " ")
- if err := enc.Encode(Msg{From: "c", Text: "hi"}); err != nil {
- fmt.Println("error:", err)
- }
- }
輸出:
- {"from":"a","text":"x \u003c y \u0026\u0026 y \u003e z"}
- {"from":"b","text":"x < y && y > z"}
- {
- "from": "c",
- "text": "hi"
- }
json.NewDecoder 串流讀取多筆資料
Decoder 從 io.Reader 一邊讀一邊解析,不需要把整份資料讀進記憶體。最常見的用途是處理「一行一筆 JSON」的格式(JSON Lines/NDJSON,常見於 log 與資料匯出):在迴圈裡反覆呼叫 Decode,讀完時回傳 io.EOF。簽名:
- func NewDecoder(r io.Reader) *Decoder
- func (dec *Decoder) Decode(v any) error
範例:
- package main
- import (
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "strings"
- )
- type LogEntry struct {
- Level string `json:"level"`
- Msg string `json:"msg"`
- }
- func main() {
- input := `{"level":"info","msg":"server start"}
- {"level":"warn","msg":"slow query"}
- {"level":"error","msg":"db down"}
- `
- dec := json.NewDecoder(strings.NewReader(input))
- for {
- var e LogEntry
- err := dec.Decode(&e)
- if errors.Is(err, io.EOF) {
- break
- }
- if err != nil {
- fmt.Println("error:", err)
- return
- }
- fmt.Printf("[%s] %s\n", e.Level, e.Msg)
- }
- }
輸出:
- [info] server start
- [warn] slow query
- [error] db down
讀 HTTP 請求時通常寫
json.NewDecoder(r.Body).Decode(&v),見 net/http。io.Reader 的概念見 io。Decoder.Token 與 More:逐筆讀取大型陣列
資料是一個很大的 JSON 陣列(例如
[{...},{...},...])時,可以先用 Token 讀掉開頭的 [,再用 More 判斷陣列裡還有沒有元素,每次 Decode 一個元素,記憶體裡同時只有一筆。Token 回傳的 json.Delim 代表 [、]、{、} 這類分隔符號。簽名:
- func (dec *Decoder) Token() (Token, error)
- func (dec *Decoder) More() bool
範例:
- package main
- import (
- "encoding/json"
- "fmt"
- "strings"
- )
- type Item struct {
- SKU string `json:"sku"`
- Qty int `json:"qty"`
- }
- func main() {
- input := `[{"sku":"A1","qty":3},{"sku":"B2","qty":5},{"sku":"C3","qty":1}]`
- dec := json.NewDecoder(strings.NewReader(input))
- tok, err := dec.Token()
- if err != nil {
- fmt.Println("error:", err)
- return
- }
- fmt.Printf("開頭:%v\n", tok)
- total := 0
- for dec.More() {
- var it Item
- if err := dec.Decode(&it); err != nil {
- fmt.Println("error:", err)
- return
- }
- total += it.Qty
- fmt.Println(it.SKU, it.Qty)
- }
- tok, _ = dec.Token()
- fmt.Printf("結尾:%v,總數 %d\n", tok, total)
- }
輸出:
- 開頭:[
- A1 3
- B2 5
- C3 1
- 結尾:],總數 9
Decoder.DisallowUnknownFields
預設情況下,JSON 裡有結構體沒有的鍵會被默默忽略。呼叫
DisallowUnknownFields 後,遇到未知鍵就回傳錯誤,適合用來驗證 API 請求或設定檔有沒有打錯字。簽名:
- func (dec *Decoder) DisallowUnknownFields()
範例:
- package main
- import (
- "encoding/json"
- "fmt"
- "strings"
- )
- type Options struct {
- Timeout int `json:"timeout"`
- Retry bool `json:"retry"`
- }
- func main() {
- input := `{"timeout":30,"retyr":true}`
- var a Options
- json.NewDecoder(strings.NewReader(input)).Decode(&a)
- fmt.Printf("預設:%+v\n", a)
- var b Options
- dec := json.NewDecoder(strings.NewReader(input))
- dec.DisallowUnknownFields()
- err := dec.Decode(&b)
- fmt.Println("嚴格:", err)
- }
輸出:
- 預設:{Timeout:30 Retry:false}
- 嚴格: json: unknown field "retyr"
json.RawMessage
RawMessage 是原封不動保留的 JSON 片段(底層是 []byte)。常見用法是「先看類型欄位,再決定剩下的內容要解成哪個結構體」,避免先解成 map[string]any 再轉換。簽名:
- type RawMessage []byte
範例:
- package main
- import (
- "encoding/json"
- "fmt"
- )
- type Envelope struct {
- Type string `json:"type"`
- Data json.RawMessage `json:"data"`
- }
- type Login struct {
- User string `json:"user"`
- }
- type Order struct {
- ID int `json:"id"`
- Total int `json:"total"`
- }
- func main() {
- inputs := []string{
- `{"type":"login","data":{"user":"alice"}}`,
- `{"type":"order","data":{"id":9,"total":300}}`,
- }
- for _, s := range inputs {
- var env Envelope
- if err := json.Unmarshal([]byte(s), &env); err != nil {
- fmt.Println("error:", err)
- continue
- }
- fmt.Println("raw:", string(env.Data))
- switch env.Type {
- case "login":
- var l Login
- json.Unmarshal(env.Data, &l)
- fmt.Printf("登入 %+v\n", l)
- case "order":
- var o Order
- json.Unmarshal(env.Data, &o)
- fmt.Printf("訂單 %+v\n", o)
- }
- }
- }
輸出:
- raw: {"user":"alice"}
- 登入 {User:alice}
- raw: {"id":9,"total":300}
- 訂單 {ID:9 Total:300}
Marshaler 與 Unmarshaler 介面
型別實作
MarshalJSON 或 UnmarshalJSON 方法時,套件會改呼叫你的方法,讓你完全掌控格式。例如把狀態碼存成 int,但 JSON 裡顯示成字串。MarshalJSON 通常用值接收者,UnmarshalJSON 必須用指標接收者才能修改值。簽名:
- type Marshaler interface {
- MarshalJSON() ([]byte, error)
- }
- type Unmarshaler interface {
- UnmarshalJSON([]byte) error
- }
範例:
- package main
- import (
- "encoding/json"
- "fmt"
- )
- type Status int
- const (
- Draft Status = iota
- Published
- )
- var names = map[Status]string{Draft: "draft", Published: "published"}
- func (s Status) MarshalJSON() ([]byte, error) {
- return json.Marshal(names[s])
- }
- func (s *Status) UnmarshalJSON(data []byte) error {
- var str string
- if err := json.Unmarshal(data, &str); err != nil {
- return err
- }
- for k, v := range names {
- if v == str {
- *s = k
- return nil
- }
- }
- return fmt.Errorf("unknown status %q", str)
- }
- type Post struct {
- Title string `json:"title"`
- Status Status `json:"status"`
- }
- func main() {
- data, _ := json.Marshal(Post{Title: "Hello", Status: Published})
- fmt.Println(string(data))
- var p Post
- err := json.Unmarshal([]byte(`{"title":"Hi","status":"draft"}`), &p)
- fmt.Println(p.Status == Draft, err)
- err = json.Unmarshal([]byte(`{"status":"deleted"}`), &p)
- fmt.Println(err)
- }
輸出:
- {"title":"Hello","status":"published"}
- true <nil>
- unknown status "deleted"
如果只是想把值轉成字串(例如當作映射的鍵),也可以實作
encoding.TextMarshaler 的 MarshalText。常見標準介面見常見標準介面。json.Valid
只檢查一段位元組是不是合法的 JSON,不解析成任何值。適合在儲存或轉送前先做一次快速檢查。
簽名:
- func Valid(data []byte) bool
範例:
- package main
- import (
- "encoding/json"
- "fmt"
- )
- func main() {
- samples := []string{
- `{"a":1}`,
- `[1,2,3]`,
- `"just a string"`,
- `{a:1}`,
- `{"a":1,}`,
- }
- for _, s := range samples {
- fmt.Printf("%-16s %v\n", s, json.Valid([]byte(s)))
- }
- }
輸出:
- {"a":1} true
- [1,2,3] true
- "just a string" true
- {a:1} false
- {"a":1,} false
重點整理
- 資料在記憶體用
Marshal/Unmarshal;從io.Reader/io.Writer讀寫用NewDecoder/NewEncoder Unmarshal與Decode一定要傳指標;只有匯出欄位會被處理,鍵名比對不分大小寫- 用 struct tag 改鍵名與省略欄位;結構體(如
time.Time)要省略零值用omitzero(Go 1.24 起) - 串流讀 JSON Lines 時反覆
Decode直到io.EOF;大型陣列用Token+More逐筆解碼 - 解碼到
any時數字是float64,大整數用UseNumber保留精度 - 需要自訂格式就實作
MarshalJSON/UnmarshalJSON,延後解析用json.RawMessage