使用未知对象取消封送 JSON



我一直在寻找我的a**,但我找不到真正帮助我的解决方案。我在围棋中有点处于初学者水平。

我有一个 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 的解决方案都是针对一些没有嵌套部件的简单结构。

我的问题既是接口(状态(又是映射[字符串]接口(操作(。我缺少什么才能将数据映射到更方便的数组或切片和接口?

很高兴任何提示为我指明正确的方向。

特雷兹

我认为你应该使用这个结构

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
}

最新更新