Consider a JSON file containing an array:
[ {"a" : "1"}, {"b" : "2"}, {"c" : "3"} ]
Despite attempting to parse it as a map of strings to strings, an error arises:
json: cannot unmarshal array into Go value of type main.data
To resolve this, we need a Go structure that mirrors the JSON array format.
The correct approach can be found here: https://play.golang.org/p/8nkpAbRzAD
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) }
This definition declares mytype as a slice of maps, aligning with the structure of the JSON array. It allows for the correct parsing and representation of the JSON data in a Go struct.
The above is the detailed content of How to Represent a JSON Array with Dynamic Keys in a Go Struct?. For more information, please follow other related articles on the PHP Chinese website!