问题描述
我正试图解组嵌套的json。一个键的值是jsons数组。数据如下:
jsonData := `{"Key0": 1,"Key1": [
{"SubKey0": "Id0","SubKey1": 0,"SubKey2": "rndm0"},{"SubKey1": "Id1","SubKey1": 1,"SubKey2": "rndm1"}
]
}'
数组中的元素数量未知且不固定。
目标是获得一个结构,其中包含数组的数据:
我尝试了以下代码:
package main
import (
"encoding/json"
"fmt"
)
type Container struct {
Key0 int
Key1 []string
}
var container Container
func main() {
jsonData := `{"Key0": 1,"Key1": [
{"SubKey0": "string0","SubKey1": 0},{"SubKey0": "string1","SubKey1": 1}
]
}`
json.Unmarshal([]byte(jsonData),&container)
fmt.Printf(string(container.Key0))
fmt.Printf(fmt.Sprint(container.Key1))
}
但这会导致container.Key1为空数组。
解决方法
JSON中的
"Key0"
是一个数字,而不是string
。
"Key1"
是一个对象数组,而不是string
的数组。
因此,请使用以下Go结构来对JSON建模:
type Container struct {
Key0 int
Key1 []map[string]interface{}
}
解析JSON:
jsonData := `{"Key0": 1,"Key1": [
{"SubKey0": "string0","SubKey1": 0},{"SubKey0": "string1","SubKey1": 1}
]
}`
if err := json.Unmarshal([]byte(jsonData),&container); err != nil {
panic(err)
}
fmt.Println(container.Key0)
fmt.Println(container.Key1)
哪个输出(在Go Playground上尝试):
1
[map[SubKey0:string0 SubKey1:0] map[SubKey0:string1 SubKey1:1]]