简体   繁体   中英

Unmarshalling json into a Golang struct with a map of structs which contains a map of structs

I'm pretty sure this can be done with multiple structs (some temporary without the maps) but I'm unsure if there is a nicer way of doing things.

Basically say I have the following structs:

type Event struct {
   Markets            map[string]Market
}
type Market struct {
   Products            map[string]Product
}
type Product struct {
   ID int
   // etc ... 
}

And I need to unmarshal json into the Events object.

If the Markets map didn't contain the Products map, I would do it like this:

var markets map[string]Market
markets = make(map[string]Market)
var e Event
e.Markets = markets
e := json.Unmarshal([]byte(jsonString), &e)

However for each market I also need to make() a Product, and for each Product I may need to create further maps etc.

I could solve this using a temporary struct, looping through and for each key calling make() (see below example) but this feels a little messy and I'm pretty sure golang would have a cleaner solution.

type TmpEvent struct {
   Markets            map[string]TmpMarket
}
type TmpMarket struct {
   // No map here, could be empty struct
}
var events Event
var e TmpEvent
var TmpMarkets map[string]TmpMarket
TmpMarkets = make(map[string]TmpMarket)
e.Markets = TmpMarket
e := json.Unmarshal([]byte(jsonString), &e)
for k, _ := range e {
   events[k].Market = make(map[string]Market)
}
// same for Product
// Then we can finally Unmarshal into original `Event` struct

Sorry if its been answered before but I couldn't find anything.

If you're just trying to unmarshal the data into Go structs, the following works:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
)

type (
    Event struct {
        Markets map[string]Market
    }
    Market struct {
        Products map[string]Product
    }
    Product struct {
        ID int
    }
)

func main() {
    content, err := ioutil.ReadFile("./data.json")
    if err != nil {
        panic(err)
    }

    var event Event
    if err := json.Unmarshal(content, &event); err != nil {
        panic(err)
    }

    fmt.Printf("%+v\n", event)
}

Given this data.json as input:

{
  "markets": {
    "foo": {
      "products": {
        "widget": {
          "id": 1
        },
        "gizmo": {
          "id": 2
        }
      }
    },
    "bar": {
      "products": {
        "doodad": {
          "id": 3
        },
        "thingy": {
          "id": 4
        }
      }
    }
  }
}

The above code outputs:

{Markets:map[bar:{Products:map[doodad:{ID:3} thingy:{ID:4}]} foo:{Products:map[gizmo:{ID:2} widget:{ID:1}]}]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM