douyao1856 2017-03-21 15:21
浏览 224
已采纳

golang解析json文件

I want to parse the following json file and also reference the individual fields.

The json file has some known pattern: The json file is has two group levels. It will have a variable but unknown number of first level groups. Each first level group will have two second level groups: the rule and config groups. Both the rule group and the config group will have unknown number of key:value pairs.

{
  { // Comment: first level group
    { // Comment: second level group
      "rule1": "doA"
      "rule2": "doB"
      "rule3": "doC"
      ...
    }
    {
      "config1": "goA"
      "configX": "goB"
      ...
    }
  }
  ...
  {
    {
      "rule100": "doAAA"
      "rule200": "doBBB"
      "rule300": "doCCC"
      ...
    }
    {
      "config100": "goAAA"
      "configX00": "goBBB"
      ...
  }
}

展开全部

  • 写回答

1条回答 默认 最新

  • dousi4950 2017-03-21 15:37
    关注

    You can use maps and slices for those unknown numbers.

    type FirstGroup struct {
        Rules Rules `json:"rules"`
        Configs Configs `json:"configs"`
    }
    
    type Rules map[string]string
    
    type Configs map[string]string
    

    https://play.golang.org/p/zCymz62B9K <- The json in this example is a modified version of your's because your's is not really json.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部