Home > Backend Development > Golang > How to Parse JSON Arrays into Go Structs?

How to Parse JSON Arrays into Go Structs?

Susan Sarandon
Release: 2024-11-26 18:01:15
Original
920 people have browsed it

How to Parse JSON Arrays into Go Structs?

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
}
Copy after login

Next, we need to define a KeysResponse struct to represent the entire array of PublicKey objects:

type KeysResponse struct {
    Collection []PublicKey
}
Copy after login

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)
}
Copy after login

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}]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template