JSON Arrays to Go Slices
Learn how JSON arrays are converted to Go slices. Covers arrays of primitives, arrays of objects, and mixed-type arrays with practical examples.
Detailed Explanation
Converting JSON Arrays to Go Slices
JSON arrays map to Go slices. The slice element type is inferred from the array contents: an array of strings becomes []string, an array of objects becomes a slice of a named struct type.
Primitive Arrays
{
"tags": ["go", "json", "api"],
"scores": [95, 87, 92]
}
type AutoGenerated struct {
Tags []string `json:"tags"`
Scores []int `json:"scores"`
}
Arrays of Objects
{
"users": [
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
]
}
type AutoGenerated struct {
Users []User `json:"users"`
}
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
The converter inspects the first element (or merges all elements) to determine the struct fields for object arrays. If elements have inconsistent shapes, the converter produces a union of all fields, using pointer types for fields that appear only in some elements.
Empty Arrays
An empty JSON array [] is ambiguous — the converter cannot determine the element type. Most converters default to []interface{} in this case. You should manually set the correct type once you know the expected data.
Nested Arrays
Arrays of arrays ([[1,2],[3,4]]) become [][]int in Go. This pattern appears in matrix data, coordinate pairs, and batch operations.
Working with Slices
for _, user := range response.Users {
fmt.Printf("User %d: %s\n", user.ID, user.Name)
}
Go slices are nil-safe for reads — iterating over a nil slice produces zero iterations, so you rarely need explicit nil checks.
Use Case
Paginated API responses, list endpoints, and bulk operations all return arrays of objects. Converting them to typed Go slices enables range-based iteration and compile-time field access.