Go の重要トピック
Go JSON: Marshal and Unmarshal
Turn structs into JSON and JSON into structs, with struct tags to choose the field names.
学べること
- json.Marshal
- json.Unmarshal
- Struct tags and omitempty
Round trip
- 1
Product{...}a struct - 2
json.Marshal{"name":"Go Book",...} - 3
json.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.
重要なポイント
- Tags choose the names used in JSON.
- Unmarshal needs a pointer.
- 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))
}
{"name":"Go Book","price":12.5,"tags":["go","learning"]}
Pen costs 1.25, tags: 0練習
サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。
このレッスンを終えましたか?
学習済みにすると進み具合を記録できます。
進み具合はこのブラウザーに保存されています ログインすると、どのデバイスでも引き継げます。
チャレンジで練習する
このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。
- JSON オブジェクトを作る キーと値を JSON オブジェクト文字列に変換し、引用符とバックスラッシュを正しくエスケープします。 簡単
- フラットな JSON の数値を合計 整数を値に持つフラットな JSON オブジェクトを解析し、値の合計を求めます。 簡単