gpt4 book ai didi

json - Golang Json编码

转载 作者:数据小太阳 更新时间:2023-10-29 03:32:53 25 4
gpt4 key购买 nike

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 {up}} {instance_raw2 {down}}]

run it on the plaground

或者这个:

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:down stop:false traffic:true label: dead:true]}]

run it on the playground

始终检查错误。上面的示例 JSON 无效,json.Unmarshal 函数报告此错误。

关于json - Golang Json编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47585926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com