使用未知对象解组JSON

使用未知对象解组JSON,json,go,struct,Json,Go,Struct,我一直在寻找我的答案,但我找不到真正有帮助的解决方案。我在围棋方面有些初级水平 我有一个JSON结构,其中有些部分可能会更改(请参阅*_changing_name),我无权更改JSON结构: { "instance" : "http://woop.tld/api/v1/health", "version" : "1.0.0", "status" : { &q

我一直在寻找我的答案,但我找不到真正有帮助的解决方案。我在围棋方面有些初级水平

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

我的问题是接口(状态)和映射[字符串]接口(操作)。 将数据映射到更方便的阵列或切片,我还缺少什么

很高兴有任何提示给我指明了正确的方向


Treize

我想,你应该使用这个结构

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
}


如果JSON对象的字段不是固定的,则必须将其解组为
map[string]X
,但X不必是
interface{}
,它可以是
int
,用于操作,例如
struct{IsAlive bool;Level int;Message string}
,用于状态。@t313下面是一个沃尔克说的例子:哇,谢谢大家。我觉得有点傻。地图[字符串]似乎很明显。嗨,Vishal,谢谢你的好例子,它很有效!
for key,_:=range healthData.Performance.Operation{
        // you will get healthData.Performance.Operation[key] as int
}