douzouchang7448 2017-09-21 11:19
浏览 148
已采纳

如何在Golang中在运行时动态设置数组的索引?

I have searched a lot about it but couldn't find the proper solution. what I am trying to do is to create the following as final output using arrays and slices in golang.

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

what I have implemented is:

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)   
}

In this IndustrySettings contains following json

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

I want to loop through this json and convert into the array like industry_id as key and form_ids as values.

Can anyone please tell how to accomplish this?

Thanks!

Edit

I mean I need output like

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

where 11 and 12 are the industry_id as given in the json to be used as key of the array and [1,2,3], [4,5] are the form ids to be set as values in the array.

  • 写回答

2条回答 默认 最新

  • dongpa6867 2017-09-23 06:10
    关注

    I think what you might want to do is define a struct that describes the JSON model you are trying to decode, unmarshal the JSON into a slice of that struct, and then loop through each decoded value, placing it in a map.

    An example of this is here: https://play.golang.org/p/Dz8XBnoVos

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 hexo+github部署博客
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?