Golang Json 编组
Golang Json marshalling
type Status struct {
slug string `json:"slug"`
}
type Instance struct {
Slug string `json:"slug"`
Stat map[string]*Status `json:"status"`
}
此 Json 响应收到 API 调用:
[ {
"status": {
"stop": false,
"traffic": true,
"label": null,
"dead": true,
"slug": "up",
},
"slug": "instances_raw",
"started_at": "15120736198",
"replacement": null
},
{
"status": {
"stop": false,
"traffic": true,
"label": null,
"dead": true,
"slug": "down",
},
"slug": "instance_raw2",
"started_at": "1512073194",
"replacement": null
}
]
我正在尝试将 json 编组到上述结构中,但 运行 编组到问题中:
instances := make([]Instance, 0)
res := api call return above json
body, _ := ioutil.ReadAll(res.Body)
json.Unmarshal(body, &instances)
fmt.Println("I am struct %s",instances)
正在编组:
I am struct %s [{ map[stop:0xc42018e1b0 dead:0xc42018e1e0 label:<nil> running:0xc42018e220 down:0xc42018e150 traffic:0xc42018e180]}]
谁能帮我弄清楚为什么它没有像我预期的那样编组?
预期编组:
[{instances_raw map[slug:up]} {instances_raw2 map[slug:down]}]
结构与数据结构不匹配。也许你想要这个:
type Status struct {
Slug string `json:"slug"`
}
type Instance struct {
Slug string `json:"slug"`
Stat Status `json:"status"`
}
输出:[{instances_raw {向上}} {instance_raw2 {向下}}]
或者这个:
type Instance struct {
Slug string `json:"slug"`
Stat map[string]interface{} `json:"status"`
}
输出:[{instances_raw map[label: dead:true slug:up stop:false traffic:true]} {instance_raw2 map[slug:向下 stop:false traffic:true 标签:dead:true]}]
经常检查错误。上面的示例 JSON 无效,json.Unmarshal 函数报告此错误。
type Status struct {
slug string `json:"slug"`
}
type Instance struct {
Slug string `json:"slug"`
Stat map[string]*Status `json:"status"`
}
此 Json 响应收到 API 调用:
[ {
"status": {
"stop": false,
"traffic": true,
"label": null,
"dead": true,
"slug": "up",
},
"slug": "instances_raw",
"started_at": "15120736198",
"replacement": null
},
{
"status": {
"stop": false,
"traffic": true,
"label": null,
"dead": true,
"slug": "down",
},
"slug": "instance_raw2",
"started_at": "1512073194",
"replacement": null
}
]
我正在尝试将 json 编组到上述结构中,但 运行 编组到问题中:
instances := make([]Instance, 0)
res := api call return above json
body, _ := ioutil.ReadAll(res.Body)
json.Unmarshal(body, &instances)
fmt.Println("I am struct %s",instances)
正在编组:
I am struct %s [{ map[stop:0xc42018e1b0 dead:0xc42018e1e0 label:<nil> running:0xc42018e220 down:0xc42018e150 traffic:0xc42018e180]}]
谁能帮我弄清楚为什么它没有像我预期的那样编组?
预期编组:
[{instances_raw map[slug:up]} {instances_raw2 map[slug:down]}]
结构与数据结构不匹配。也许你想要这个:
type Status struct {
Slug string `json:"slug"`
}
type Instance struct {
Slug string `json:"slug"`
Stat Status `json:"status"`
}
输出:[{instances_raw {向上}} {instance_raw2 {向下}}]
或者这个:
type Instance struct {
Slug string `json:"slug"`
Stat map[string]interface{} `json:"status"`
}
输出:[{instances_raw map[label: dead:true slug:up stop:false traffic:true]} {instance_raw2 map[slug:向下 stop:false traffic:true 标签:dead:true]}]
经常检查错误。上面的示例 JSON 无效,json.Unmarshal 函数报告此错误。