[英]Infinite struct with JSON and Golang
我不知道如何用 Golang 解组这种 JSON 结构。 我从 REST API 得到响应。键是动态的,嵌套的键和值也是动态的..
{"key1":{"col1":"Data11","col2":"Data12","col3":"Data13","col4":"Data14"},
"key2":{"col1":"Data21","col2":"Data22","col3":"Data23","col4":"Data24"},
"key3":{"col1":"Data31","col2":"Data32","col3":"Data33","col4":"Data34"},
"key4":{"col1":"Data41","col2":"Data42","col3":"Data43","col4":"Data44"},
"key5":{"col1":"Data51","col2":"Data52","col3":"Data53","col4":"Data54"},
"key6":{"col1":"Data61","col2":"Data62","col3":"Data63","col4":"Data64"}}
我尝试使用 JsonToStruct 并且很明显地得到了这个:
type AutoGenerated struct {
Key1 struct {
Col1 string `json:"col1"`
Col2 string `json:"col2"`
Col3 string `json:"col3"`
Col4 string `json:"col4"`
} `json:"key1"`
Key2 struct {
Col1 string `json:"col1"`
Col2 string `json:"col2"`
Col3 string `json:"col3"`
Col4 string `json:"col4"`
} `json:"key2"`
Key3 struct {
Col1 string `json:"col1"`
Col2 string `json:"col2"`
Col3 string `json:"col3"`
Col4 string `json:"col4"`
} `json:"key3"`
Key4 struct {
Col1 string `json:"col1"`
Col2 string `json:"col2"`
Col3 string `json:"col3"`
Col4 string `json:"col4"`
} `json:"key4"`
Key5 struct {
Col1 string `json:"col1"`
Col2 string `json:"col2"`
Col3 string `json:"col3"`
Col4 string `json:"col4"`
} `json:"key5"`
Key6 struct {
Col1 string `json:"col1"`
Col2 string `json:"col2"`
Col3 string `json:"col3"`
Col4 string `json:"col4"`
} `json:"key6"`
}
但是我不知道我将在响应中获得的密钥的名称,因此我需要一个通用的解组。 我卡住了。
您需要将数据解组为 map[string]map[string]string,如下所示:
jsonData:="{\"key1\":{\"col1\":\"Data11\",\"col2\":\"Data12\",\"col3\":\"Data13\",\"col4\":\"Data14\"}, \"key2\":{\"col1\":\"Data21\",\"col2\":\"Data22\",\"col3\":\"Data23\",\"col4\":\"Data24\"}, \"key3\":{\"col1\":\"Data31\",\"col2\":\"Data32\",\"col3\":\"Data33\",\"col4\":\"Data34\"}, \"key4\":{\"col1\":\"Data41\",\"col2\":\"Data42\",\"col3\":\"Data43\",\"col4\":\"Data44\"}, \"key5\":{\"col1\":\"Data51\",\"col2\":\"Data52\",\"col3\":\"Data53\",\"col4\":\"Data54\"}, \"key6\":{\"col1\":\"Data61\",\"col2\":\"Data62\",\"col3\":\"Data63\",\"col4\":\"Data64\"}}"
var jsonObject map[string]map[string]string
json.Unmarshal([]byte(jsonData),&jsonObject)
for k:=range jsonObject{
fmt.Println(k ," has " , len(jsonObject[k]) , " fields")
for j:=range jsonObject[k]{
fmt.Println(j , "=",jsonObject[k][j] )
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.