CodexBloom - Programming Q&A Platform

advanced patterns When Parsing JSON with Nested Arrays in Go - Index Out of Range scenarios

👀 Views: 0 💬 Answers: 1 📅 Created: 2025-08-07
go json parsing Go

I'm sure I'm missing something obvious here, but I'm currently working on parsing a JSON response that contains nested arrays using Go, specifically version 1.18. The JSON structure looks like this: ```json { "name": "example", "items": [ { "id": 1, "tags": ["tag1", "tag2"] }, { "id": 2, "tags": ["tag3"] } ] } ``` I have defined my structs as follows: ```go type Item struct { ID int `json:"id"` Tags []string `json:"tags"` } type Response struct { Name string `json:"name"` Items []Item `json:"items"` } ``` When I try to unmarshal this JSON response with the following code: ```go var response Response err := json.Unmarshal(data, &response) if err != nil { log.Fatal(err) } ``` I receive an `index out of range` behavior when I try to access the Tags of the second item: ```go fmt.Println(response.Items[1].Tags[1]) ``` This results in the behavior: `panic: runtime behavior: index out of range [1] with length 1`. I expected to retrieve `"tag3"` from the second item, but the behavior indicates that the Tags array only has a single element. I've checked the JSON data multiple times and it appears to be formatted correctly. I’ve also tried adding behavior checking after unmarshalling to ensure the data is being parsed correctly, but the behavior continues. Can anyone provide insight into why this might be happening or how to safely access the tags without working with an index out of range behavior? My development environment is Windows.