jisan
jisan

Reputation: 233

How can I parse the following JSON structure in Go

In Go, how can I parse the following JSON? I know to use struct to parse, but the keys are different for each entry, 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 help!

Upvotes: 5

Views: 387

Answers (3)

tez
tez

Reputation: 435

You can also provide Go' structure for more fluent 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"`
}

Working example on playground

Upvotes: 0

Thundercat
Thundercat

Reputation: 120931

Unmarshal the JSON to a map type: map[string][]string

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

playground example

Upvotes: 2

Tarsis Azevedo
Tarsis Azevedo

Reputation: 1523

If json values are always an []string you can convert it with

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

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

Upvotes: 7

Related Questions