JSONから構造体へ変換する方法
JSONを構造体にアンマーシャルするには、encoding/jsonパッケージが提供するUnmarshal関数を使えます。例えばです。
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Emails []string `json:"emails"`
Address struct {
City string `json:"city"`
Country string `json:"country"`
} `json:"address"`
}
func main() {
jsonData := `{
"name": "John Doe",
"age": 30,
"emails": ["john@example.com", "johndoe@example.com"],
"address": {
"city": "New York",
"country": "USA"
}
}`
var person Person
err := json.Unmarshal([]byte(jsonData), &person)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Name:", person.Name)
fmt.Println("Age:", person.Age)
fmt.Println("Emails:", person.Emails)
fmt.Println("Address:", person.Address)
}
この例では、Person 構造体を定義して、そのフィールドを JSON のキーに関連付けます。次に、json.Unmarshal 関数を使用して、JSON データを構造体変数に解析します。最後に、解析された構造体のフィールドにアクセスできます。
結果は以下の通り
Name: John Doe
Age: 30
Emails: [john@example.com johndoe@example.com]
Address: {New York USA}
JSONを構造体にマッピングできました。