我一直在搜寻我的**,但找不到真正帮助我的解决方案。我现在处于入门阶段。
我有一个JSON结构,其中某些部分可能会更改(请参阅* _changing_name),并且我无权更改JSON结构:
{
"instance" : "http://woop.tld/api/v1/health",
"version" : "1.0.0",
"status" : {
"Service1_changing_name" : {
"isAlive" : true,
"level" : 6,
"message" : "Running under normal conditions"
},
"Service2_changing_name" : {
"isAlive" : true,
"level" : 1,
"message" : "Critical condition"
}
},
"errors" : {
"level" : 1,
"messages" : [
"Service2 is in critical condition"
]
},
"performance" : {
"operation" : {
"changing_name1" : 10,
"changing_name2" : 19839,
"changing_name3" : 199,
"changing_name4" : 99
}
}
}
我正在使用此结构来解组JSON:
// HealthData object
type HealthData struct {
Instance string `json:"instance"`
Version string `json:"version"`
Status interface {
} `json:"status"`
Errors struct {
Level int `json:"level"`
Messages []string `json:"messages"`
} `json:"errors"`
Performance struct {
Operation map[string]interface {
} `json:"operation"`
} `json:"performance"`
}
我发现的大多数Stackoverflow解决方案都是针对一些没有嵌套部件的简单结构。
我的问题是接口(状态)和map [string]接口(操作)。在映射和接口中将数据保存到更方便的数组或切片时,我缺少什么?
很高兴能为我指明正确的方向。
十三
我认为,您应该使用此结构
type HealthData struct {
Instance string `json:"instance"`
Version string `json:"version"`
Status map[string]struct {
IsAlive bool `json:"isAlive"`
Level int `json:"level"`
Message string `json:"message"`
} `json:"status"`
Errors struct {
Level int `json:"level"`
Messages []string `json:"messages"`
} `json:"errors"`
Performance struct {
Operation map[string]int `json:"operation"`
} `json:"performance"`
}
然后,元帅的工作就像一种魅力。
healthData:=HealthData{}
if err:=json.Unmarshal(jsonData,&healthData); err!=nil{//error handling}
在映射和接口中将数据保存到更方便的数组或切片时,我缺少什么?
为此,只需使用for循环,就像这样
for key,_:=range healthData.Status{
// you will get healthData.Status[key] as struct
}
和
for key,_:=range healthData.Performance.Operation{
// you will get healthData.Performance.Operation[key] as int
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句