MKB
MKB

Reputation: 815

How to dynamically set index of an array on run time in 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.

Upvotes: 0

Views: 1429

Answers (2)

Opnauticus
Opnauticus

Reputation: 670

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

Upvotes: 1

Ravi R
Ravi R

Reputation: 1782

A more efficient way may be to write a customized JSON decode function and decode it into a map with key as your industry_id. But if you must use an array/slice it can be something on these lines (the first argument to the add function index can be your industry_id - change mystruct definition to whatever you need):

package main

import (
    "fmt"
)

type mystruct []int

var ns []mystruct

func main() {

    ns = make([]mystruct, 1, 1)

    add(1, []int{2222, 24, 34})
    add(7, []int{5})
    add(13, []int{4,6,75})
    add(14, []int{8})
    add(16, []int{1, 4, 44, 67, 77})

    fmt.Println("Hello, playground", ns)
}

func add(index int, ms mystruct) {

    nscap := cap(ns)
    nslen := len(ns)
    //fmt.Println(nscap, nslen, index, ms)

    if index >= nscap {
        //Compute the new nslen & nscap you need
        //This is just for a sample - doubling it

        newnscap := index * 2
        newnslen := newnscap - 1

        nstemp := make([]mystruct, newnslen, newnscap)
        copy(nstemp, ns)
        ns = nstemp

        fmt.Println("New length and capacity:", cap(ns), len(ns))

        nscap = cap(ns)
        nslen = len(ns)
    }
    //Capacity and length may have changed above, check
    if index < nscap && index >= nslen {
        fmt.Println("Extending slice length",  nslen, "to capacity", nscap)
        ns = ns[:nscap]
    }
    ns[index] = ms
}

On playground: https://play.golang.org/p/fgcaM1Okbl

Upvotes: 0

Related Questions