使用未知密钥麻烦解组嵌套的json [英] Trouble unmarshalling nested json with unknown keys
问题描述
我在将以下格式的json数据解组到结构时遇到麻烦. json的结构对我来说有点令人困惑,因此对我为取消封送而做的所有愚蠢的事情表示歉意.
I am having trouble unmarshalling a json data of the below format to a struct. The structure of the json looks a bit confusing to me, so apologies for all the dumb things I am doing to unmarshal it.
{
"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
}
我正在尝试使用以下结构对其进行解组.
I am trying to unmarshal it using the following struct.
type ServerDetails struct {
Message struct{
Hostname struct{
Details struct{
Application string `json:"application"`
}`json:"-"`
}`json:"-"`
}`json:"message"`
}
字段Server[0-9].example.com
在生成时将是未知的,并且会发生变化,并且存在此字段
The fields Server[0-9].example.com
will be unknown at the time of generating, and will change, and there is this field
{
"application": "Apache",
"host": {
"name": "/^Server-[13456]/"
},
紧跟在没有外部密钥的服务器名称之后,这再次让我感到困惑.我尝试了很多组合以了解如何将其解组,但是我失败了.
just after the server name that doesn't have a key outside, which again looks confusing to me. I tried a good number of combinations to understand how this could be unmarshalled, but I failed.
什么是使json字段解组为结构的有效方法?
What is a working approach to get the json fields unmarshal into a struct?
推荐答案
您可以包含map [string] ServerStruct来满足您的要求.
You could include a map[string]ServerStruct to fullfill your requirements.
您的结构可能看起来像这样:
your struct could look like this:
type YourStruct struct {
Success bool
ResponseMS int
Servers map[string]*ServerStruct
}
type ServerStruct struct {
Application string
Owner string
[...]
}
使用一些其他json标签,您将能够解析json.
With some additional json tags, you will be able to parse your json.
这篇关于使用未知密钥麻烦解组嵌套的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!