解析未知的JSON对象
时间:2024-02-19
浏览:269
作者:佚名
本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《解析未知的JSON对象》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~
问题内容
我一直在寻找我的**,但我找不到真正帮助我的解决方案。我在 go 方面处于初级水平。
我有一个 json 结构,其中某些部分可能会更改(请参阅 *_chang_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"`
}
那么 unmarshal 就可以发挥作用了。
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
}理论要掌握,实操不能落!以上关于《解析未知的JSON对象》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
