Parsing JSON Array into Data Structure in Go
When dealing with JSON data structured as an array, utilizing a Go map might encounter limitations. A more suitable approach is to define a custom data structure to accommodate the specific format of the data.
An example JSON array:
[ {"a" : "1"}, {"b" : "2"}, {"c" : "3"} ]
To parse this array, a custom type can be defined:
type mytype []map[string]string
This type represents an array of maps, where each map element corresponds to an object in the JSON array.
Here's how to parse the JSON array into the custom type:
package main 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) }
By reading the file and unmarshaling its contents into the data variable of type mytype, the JSON array is successfully parsed into a Go structure. The data variable can then be used to access the individual objects in the array.
The above is the detailed content of How to Efficiently Parse a JSON Array into a Go Data Structure?. For more information, please follow other related articles on the PHP Chinese website!