gpt4 book ai didi

arrays - 如何在 golang 运行时动态设置数组的索引?

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

我已经搜索了很多,但找不到合适的解决方案。我想要做的是使用 golang 中的数组和 slice 创建以下内容作为最终输出。

[
11 => [1,2,3],
12 => [4,5],
]

我实现的是:

type Industries struct {
IndustryId int `json:"industry_id"`
FormIds []int `json:"form_ids"`
}


var IndustrySettings IndustrySettings
_ := json.NewDecoder(c.Request.Body).Decode(&IndustrySettings)
var industryArr []int

for _, val := range IndustrySettings.IndustrySettings {
industryArr = append(industryArr, val.IndustryId)
}

在此 IndustrySettings 中包含以下 json

{
"industry_settings": [{
"industry_id": 11,
"form_ids": [1, 2, 3]
},
{
"industry_id": 12,
"form_ids": [4, 5]
}
]
}

我想遍历这个 json 并转换成数组,例如 industry_id 作为键,form_ids 作为值。

谁能告诉我如何完成这个?

谢谢!

编辑

我的意思是我需要这样的输出

[
11 => [1,2,3],
12 => [4,5],
]

其中 1112 是 json 中给出的用作数组键的 industry_id 和 [1,2,3], [4,5] 是要设置为数组中值的表单 ID。

最佳答案

我认为您可能想要做的是定义一个结构来描述您尝试解码的 JSON 模型,将 JSON 解码为该结构的一部分,然后遍历每个解码值,将其放入映射中。

这里有一个例子: https://play.golang.org/p/Dz8XBnoVos

关于arrays - 如何在 golang 运行时动态设置数组的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46342596/

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