How to Parse the JSON Array in Go?
In Go, parsing JSON arrays is a common task when working with APIs or structured data sources. To achieve this, you can follow these steps:
-
Define a struct: First, define a Go struct that will represent the data in each element of the JSON array. The struct should have fields that correspond to the properties of the objects within the array.
type PublicKey struct {
Name string
Price string
}
Copy after login
-
Unmarshalling the JSON: Once you have defined the struct, you can unmarshal the JSON array into a slice of the struct using the json.Unmarshal() function.
keys := make([]PublicKey,0)
err := json.Unmarshal([]byte(s), &keys)
Copy after login
-
Handling Errors: Check for any errors that may have occurred during unmarshalling and print them out for debugging.
if err != nil {
fmt.Println(err)
fmt.Printf("%+v\n", keys)
}
Copy after login
-
Working with the Parsed Data: If the unmarshalling was successful, you can work with the parsed data via the slice keys. This data represents an array of PublicKey objects.
if err == nil {
fmt.Printf("%+v\n", keys)
}
Copy after login
Note: Ensure that the JSON array's field names match the struct field names. If they differ, you can use struct tags to specify the JSON property names corresponding to each field.
The above is the detailed content of How to Parse a JSON Array in Go?. For more information, please follow other related articles on the PHP Chinese website!