Go json and embedded struct

使用 embedded struct 做 json 的 marshal 跟 unmarshal 時,json 欄位會省略 struct embedded 欄位的中間名,以比較簡潔的形式呈現。如果 struct 有寫出欄位名稱,json 欄位就會多那一層。

使用 embedded struct

1
2
3
4
5
6
7
8
9
10
11
type Serving struct {
Amount float64
Unit string
}

type Food struct {
Name string
Serving // embedded struct
NutritionInfo
Comment string
}

marshal 結果:

1
2
3
4
5
6
7
8
9
10
{
"Name":"Banana",
"Amount":100,
"Unit":"g",
"Calorie":0,
"Carb":0,
"Fat":0,
"Protein":0,
"Comment":""
}

不使用 embedded struct

1
2
3
4
5
6
type Food struct {
Name string
Serving Serving // not embedded struct
NutritionInfo
Comment string
}

marshal 結果:

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"Name":"Banana",
"Serving":
{
"Amount":100,
"Unit":"g"
},
"Calorie":0,
"Carb":0,
"Fat":0,
"Protein":0,
"Comment":""
}

不用 embeded struct 就會有一層 Serving,用 embedded struct 就會省略 Serving 這層。