Golang使用未知键解编嵌套json时遇到困难
问题描述:
我无法将以下格式的json数据解组到一个结构。 json的结构对我来说看起来有些困惑,所以我为解开所有愚蠢的事情而表示歉意。Golang使用未知键解编嵌套json时遇到困难
{
"message": {
"Server1.example.com": [
{
"application": "Apache",
"host": {
"name": "/^Server-[13456]/"
},
"owner": "User1",
"project": "Web",
"subowner": "User2"
}
],
"Server2.example.com": [
{
"application": "Mysql",
"host": {
"name": "/^Server[23456]/"
},
"owner": "User2",
"project": "DB",
"subowner": "User3"
}
]
},
"response_ms": 659,
"success": true
}
我想使用下面的结构解组它。
type ServerDetails struct {
Message struct{
Hostname struct{
Details struct{
Application string `json:"application"`
}`json:"-"`
}`json:"-"`
}`json:"message"`
}
的字段Server[0-9].example.com
将在发生的时间未知,而且将改变,并有该领域
{
"application": "Apache",
"host": {
"name": "/^Server-[13456]/"
},
刚过不具有外部密钥的服务器名称,再次让我感到困惑。我尝试了很多组合来理解这可能如何解组,但我失败了。
什么是工作的方法来获取json字段unmarshal到结构?有人可以帮我理解这个吗?
谢谢。
答
你可以包括地图[字符串] ServerStruct满足您的需求。
你的结构看起来是这样的:
type YourStruct struct {
Success bool
ResponseMS int
Servers map[string]*ServerStruct
}
type ServerStruct struct {
Application string
Owner string
[...]
}
随着一些额外的JSON标签,您将能够分析您的JSON。
答
你JSON是不符合秒] 后多余的逗号有效一旦你正确的JSON,你可以使用优秀的https://mholt.github.io/json-to-go/建立以下转到结构
type AutoGenerated struct {
Message struct {
Server1ExampleCom []struct {
Application string `json:"application"`
Host struct {
Name string `json:"name"`
} `json:"host"`
Owner string `json:"owner"`
Project string `json:"project"`
Subowner string `json:"subowner"`
} `json:"Server1.example.com"`
Server2ExampleCom []struct {
Application string `json:"application"`
Host struct {
Name string `json:"name"`
} `json:"host"`
Owner string `json:"owner"`
Project string `json:"project"`
Subowner string `json:"subowner"`
} `json:"Server2.example.com"`
} `json:"message"`
ResponseMs int `json:"response_ms"`
Success bool `json:"success"`
}
使用'map [string] whateverstruct'使用各种键解组对象。 – Volker
谢谢@Volker,你救了我的一天。我做了相应的修改,并且工作。你可以将它添加为答案,我会接受它。 – scott