0

I'm new to Go and can't create a map of multiple structures

type ResultMap struct {
    title string
    shope  Shope 
}

type Shope struct {
    title  string
    prices PriceModel
}

type PriceModel struct {
    price, priceSale float64
}

I want to get a map like this with multiple shops:

{
  "title": "Foo",
  "shope": {
     "title": "Matket_1",
     "prices": {
       "price": 100.5,
       "priceSale": 99.5
     }
  },
  "shope": {
     "title": "Matket_2",
     "prices": {
       "price": 100.5,
       "priceSale": 99.5
     }

  //...

  //Market_3
  //Market_4
}

I get the data from the loop and try to add it to the map:

for _, i := range shoplist {
  priceList := ResultMap{
            title: i,
            shope: Shope{
                title: i.shope,
                prices: PriceModel{
                    price: i.price,
                    priceSale: i.priceSale,
                },
            },

            // try
            shope: Shope{
                title: i.shope,
                prices: PriceModel{
                    price: i.price,
                    priceSale: i.priceSale,
                },
            }
           // errore            
        }

I realize that a list needs to be created somewhere, but I don't know exactly where to create it

nikar
  • 9
  • 2
  • 4
    This is a bit difficult to answer as your `struct` does not contain a `map` or slice, and your example JSON has duplicate keys ([not recommended](https://stackoverflow.com/a/23195243/11810946)) . Did you, perhaps, intend something [like this](https://go.dev/play/p/SJyN81XxUk3)? – Brits Aug 03 '23 at 03:27
  • 1
    When you say "I want to get a map like this with multiple shops" you should explicitly state that your desired example is JSON. That is not a Go map representation. In fact, your question would benefit from being reworded to make it clearer that you want to know how to produce a particular JSON representation given a set of Go structures. Your code also does not show how you are trying to convert the Go structure to JSON. Hint: Your `type ResultMap` should define a list of `Shope`: `shope []Shope`. – Kurtis Rader Aug 03 '23 at 06:22
  • Go is statically typed, you cannot do what you want (at least directly). Redesign (use e.g. interface or manuyl union types). – Volker Aug 03 '23 at 08:24

1 Answers1

-1

You can use this site to create golang struct or map from a json : https://transform.tools/json-to-go

Md Kamruzzaman
  • 346
  • 1
  • 8