golang parsing json file

huangapple go评论77阅读模式
英文:

golang parsing json file

问题

我想解析以下的 JSON 文件,并引用各个字段。

该 JSON 文件具有一些已知的模式:该文件有两个层级的分组。它将具有一个可变但未知数量的第一层级分组。每个第一层级分组将具有两个第二层级分组:rule 组和 config 组。rule 组和 config 组都将具有未知数量的键值对。

{
  { // 注释:第一层级分组
    { // 注释:第二层级分组
      "rule1": "doA",
      "rule2": "doB",
      "rule3": "doC",
      ...
    },
    {
      "config1": "goA",
      "configX": "goB",
      ...
    }
  },
  ...
  {
    {
      "rule100": "doAAA",
      "rule200": "doBBB",
      "rule300": "doCCC",
      ...
    },
    {
      "config100": "goAAA",
      "configX00": "goBBB",
      ...
    }
  }
}

请注意,我只提供了翻译的部分,不包括代码部分。

英文:

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

得分: 3

你可以使用mapslice来处理那些未知的数字。

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 <- 这个示例中的 JSON 是你的修改版本,因为你的 JSON 实际上不是有效的 JSON。

英文:

You can use maps and slices for those unknown numbers.

type FirstGroup struct {
	Rules Rules `json:&quot;rules&quot;`
	Configs Configs `json:&quot;configs&quot;`
}

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.

huangapple
  • 本文由 发表于 2017年3月22日 07:21:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/42940026.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定