How can I parse the following JSON structure in Go

In Go, how can I parse the next JSON? I know to use structfor parsing, but the keys are different for each record, also they are not fixed, they can be more or less.

{
  "consul": [],
  "docker": [],
  "etcd": ["etcd"],
  "kubernetes": ["secure"],
  "mantl-api": [],
  "marathon": ["marathon"],
  "mesos": ["agent", "follower", "leader", "master"],
  "mesos-consul": [],
  "zookeeper": ["mantl"]
}

Thanks for the help!

+4
source share
3 answers

If json values ​​are always []string, you can convert them using

json.Unmarshal(value, &map[string][]string)

But if not, the best way to do this is Unmarshal JSON in the map [string] {} interface and check each type of field you want.

+6
source

Cancel JSON on map type: map[string][]string

var m map[string][]string
if err := json.Unmarshal(data, &m); err != nil {
    // handle error
}

playground example

+2
source

Go ' unmarshaling...

type Rec struct {
    Consul      []string // `json:"consul"`
    Docker      []string // `json:"docker"`
    Etcd        []string // `json:"etcd"`
    Kubernetes  []string // `json:"kubernetes"`
    MantlApi    []string // `json:"mantl-api"`
    Marathon    []string // `json:"marathon"`
    Mesos       []string // `json:"mesos"`
    MesosConsul []string // `json:"mesos-consul"`
    Zookeeper   []string // `json:"zookeeper"`
}

0

All Articles