douyao1856 2017-03-21 23: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 23: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.

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

报告相同问题?