In Golang, parsing JSON data into custom data structures can be straightforward. Consider a scenario where a JSON file contains an array of objects with dynamic keys:
[ {"a" : "1"}, {"b" : "2"}, {"c" : "3"} ]
Attempting to parse this JSON into a map[string]string may result in an error:
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 }
To resolve this issue and parse the JSON array, a custom type mytype is defined as an array of maps:
type mytype []map[string]string
By defining the data structure as a slice of maps, the JSON array can be parsed accordingly:
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) }
This approach allows for parsing of JSON arrays with dynamic keys into a Go data structure.
The above is the detailed content of How to Parse JSON Arrays with Dynamic Keys into Go Data Structures?. For more information, please follow other related articles on the PHP Chinese website!