Handling JSON Parsing Errors in Go with Custom Structs and Nested Arrays
I'm a bit lost with I'm integrating two systems and I've encountered a strange issue with I'm working with Go (version 1.19) to parse a JSON response from an API that returns user data, which includes an array of friends for each user... The JSON structure looks something like this: ```json { "users": [ { "id": 1, "name": "Alice", "friends": [ {"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"} ] }, { "id": 4, "name": "Dave", "friends": [] } ] } ``` I have defined my struct in Go as follows: ```go type Friend struct { ID int `json:"id"` Name string `json:"name"` } type User struct { ID int `json:"id"` Name string `json:"name"` Friends []Friend `json:"friends"` } type Response struct { Users []User `json:"users"` } ``` When I attempt to unmarshal the JSON response using the following code: ```go var response Response err := json.Unmarshal(data, &response) if err != nil { log.Fatal(err) } ``` I encounter the behavior: `json: want to unmarshal array into Go struct field Response.users of type main.User`. I initially thought this might be related to using the wrong types in my structs, but they seem to match the JSON structure correctly. I've also checked that the `data` variable contains the JSON as a byte slice. To troubleshoot, I've printed the raw JSON string before unmarshalling, and it looks fine. Is there a potential scenario with the way the JSON is structured, or could this be an scenario with how I'm defining my structs? Any guidance would be appreciated as I don't want to resort to any manual parsing if possible. Cheers for any assistance! This is part of a larger desktop app I'm building. Thanks for any help you can provide! My development environment is Linux. What would be the recommended way to handle this?