Reputation: 233
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
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"`
}
Upvotes: 0
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
}
Upvotes: 2
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