Parsing JSON Arrays into Go Data Structures
When dealing with JSON data containing arrays, it can be challenging to choose the appropriate Go data structure to parse into. For instance, if a file holds an array of key-value pairs, attempts to utilize a map[string]string may result in an error like "cannot unmarshal array into Go value of type main.data."
The solution lies in accurately identifying the JSON structure. While the provided example appears to be an array, it is in fact an array of maps. The file should instead resemble the following to match the map[string]string structure:
{ "a":"1", "b":"2", "c":"3" }
Consider the following code snippet that demonstrates parsing an array of maps into a Go struct:
package main import ( "encoding/json" "fmt" "io/ioutil" "log" ) type mytype []map[string]string 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) }
When you run this code with a valid JSON file, it will successfully parse the data into the desired structure, providing you with access to the key-value pairs in the array.
The above is the detailed content of How Do I Parse JSON Arrays of Maps into Go Structs?. For more information, please follow other related articles on the PHP Chinese website!