How to Process JSON Arrays in Go
The query presents a challenge in parsing JSON arrays in Go. A JSON array is a collection of objects, and in the given example, the data returned from an API call is an array of complex objects.
To parse this array, we need to define a Go struct that reflects the structure of the objects in the array. Let's start by defining the PublicKey struct:
type PublicKey struct { name string price string }
Next, we need to define a KeysResponse struct to represent the entire array of PublicKey objects:
type KeysResponse struct { Collection []PublicKey }
We then unmarshal the JSON into a variable of type KeysResponse:
keys := make([]PublicKey, 0) err := json.Unmarshal([]byte(s), &keys) if err == nil { fmt.Printf("%+v\n", keys) } else { fmt.Println(err) fmt.Printf("%+v\n", keys) }
The json.Unmarshal function will automatically populate the keys variable with the parsed data from the JSON. However, the original question's code contained an overlooked detail: the fields of the PublicKey struct need to be exported (start with an uppercase letter).
After making this change, the code will correctly parse the JSON array and output the results in the desired format:
[{Name:Galaxy Nexus Price:3460.00} {Name:Galaxy Nexus Price:3460.00}]
Note that the JSON text in the question contains field names with lowercase letters, but the json package is intelligent enough to match them with the exported fields of the PublicKey struct.
For a more complex JSON structure, it's recommended to use struct tags to explicitly map JSON field names to struct fields. Additionally, unmarshaling into a slice of maps ([]map[string]interface{}) provides an alternative approach but requires manual indexing and type assertions.
The above is the detailed content of How to Parse JSON Arrays into Go Structs?. For more information, please follow other related articles on the PHP Chinese website!