doumeng4400
doumeng4400
2016-07-13 00:48

如何在Go中解析以下JSON结构

已采纳

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!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • douchuituo3032 douchuituo3032 5年前

    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.

    点赞 评论 复制链接分享
  • doudi5892 doudi5892 5年前

    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

    点赞 评论 复制链接分享
  • dongyan3853 dongyan3853 5年前

    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

    点赞 评论 复制链接分享

为你推荐