本篇文章說明 encoding/json 部分函式,JSON 和 byte[] 轉換,還有透過 map 只轉換特定屬性
Official Document
struct 轉換 JSON (Marshal)
1
| func Marshal(v any) ([]byte, error)
|
1 2 3 4 5 6 7 8 9 10 11
| type Person struct { ID int Name string }
person := Person{ ID: 1, Name: "Bob", } jsonBlob, _ := json.Marshal(person) os.Stdout.Write(jsonBlob)
|
JSON 轉換 struct (Unmarshal)
1
| func Unmarshal(data []byte, v any) error
|
1 2 3 4 5 6 7 8 9
| type Person struct { ID int Name string }
var jsonBlob = []byte(`{"id": 1, "name": "Bob"}`) var person Person json.Unmarshal(jsonBlob, &person) fmt.Printf("%+v", person)
|
JSON 轉換指定屬性 struct
使用 map 處理這個功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| func Unmarshal(data []byte, v any) error
type Name struct { First string Last string }
type Person struct { ID int Name Name }
var jsonBlob = []byte(`{"ID": 1, "Name": { "First": "Chen", "Last": "Bob" }}`) var obj map[string]json.RawMessage var name Name json.Unmarshal(jsonBlob, &obj) json.Unmarshal(obj["Name"], &name) fmt.Printf("%+v", name)
|
json/struct 屬性對應
1 2 3 4
| type Person struct { ID int `json:"id"` Name string `json:"name"` }
|
1 2 3 4 5 6
| person := Person{ ID: 1, Name: "Bob", } jsonBlob, _ := json.Marshal(person) os.Stdout.Write(jsonBlob)
|
1 2 3 4
| var jsonBlob = []byte(`{"id": 1, "name": "Bob"}`) var person Person json.Unmarshal(jsonBlob, &person) fmt.Printf("%+v", person)
|
只取需要屬性
1 2 3 4 5 6 7 8
| type Person struct { Name string `json:"name"` }
var jsonBlob = []byte(`{"id": 1, "name": "Bob"}`) var person Person json.Unmarshal(jsonBlob, &person) fmt.Printf("%+v", person)
|