英文:
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
你可以使用map
和slice
来处理那些未知的数字。
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 map
s and slice
s 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论