How to Parse JSON Array in Go
In Go, the encoding/json package provides support for unmarshalling JSON data into Go structures. To parse a JSON array, you can use the following steps:
Define a Go struct: Define a struct that represents the shape of the individual elements in the JSON array. For example, if the JSON array contains objects with name and price fields, you would define the following struct:
type PublicKey struct { Name string Price string }
Note: Ensure that the field names in the struct match the field names in the JSON array.
Create a slice of the struct: Create a slice of the defined struct type to hold the parsed data:
var keys []PublicKey
Unmarshal the JSON: Use the json.Unmarshal() function to unmarshal the JSON array into the slice of structs:
err := json.Unmarshal([]byte(jsonStr), &keys)
where jsonStr is the JSON data to be parsed.
Handle any errors: Check for any errors encountered during unmarshalling. If an error occurs, it will be stored in the err variable:
if err != nil { // Handle the error }
Access the parsed data: Once the JSON array is parsed, you can access the individual elements of the slice of structs:
for _, key := range keys { fmt.Println(key.Name, key.Price) }
Example:
The following code demonstrates how to parse a JSON array using the above steps:
package main import ( "encoding/json" "fmt" ) type PublicKey struct { Name string Price string } func main() { jsonStr := `[{"name":"Galaxy Nexus", "price":"3460.00"},{"name":"Galaxy Nexus", "price":"3460.00"}]` var keys []PublicKey err := json.Unmarshal([]byte(jsonStr), &keys) if err == nil { for _, key := range keys { fmt.Println(key.Name, key.Price) } } else { fmt.Println(err) } }
Output:
Galaxy Nexus 3460.00 Galaxy Nexus 3460.00
The above is the detailed content of How do I parse a JSON array in Go?. For more information, please follow other related articles on the PHP Chinese website!