在 Golang 中,将 JSON 数据解析为自定义数据结构非常简单。考虑一个场景,其中 JSON 文件包含具有动态键的对象数组:
[ {"a" : "1"}, {"b" : "2"}, {"c" : "3"} ]
尝试将此 JSON 解析为 map[string]string 可能会导致错误:
import ( "encoding/json" "io/ioutil" "log" ) type data map[string]string func main() { c, _ := ioutil.ReadFile("test.json") dec := json.NewDecoder(bytes.NewReader(c)) var d data dec.Decode(&d) // error: cannot unmarshal array into Go value of type data }
为了解决这个问题并解析 JSON 数组,自定义类型 mytype 被定义为映射数组:
type mytype []map[string]string
通过定义数据将结构视为映射的切片,可以相应地解析 JSON 数组:
import ( "encoding/json" "fmt" "io/ioutil" "log" ) func main() { var data mytype file, err := ioutil.ReadFile("test.json") if err != nil { log.Fatal(err) } err = json.Unmarshal(file, &data) if err != nil { log.Fatal(err) } fmt.Println(data) }
这种方法允许将具有动态键的 JSON 数组解析为 Go 数据结构。
以上是如何将带有动态键的 JSON 数组解析为 Go 数据结构?的详细内容。更多信息请关注PHP中文网其他相关文章!