12/04/2026 18:19pm

EP.13.1 Go and JSON Array - Easily Manage Multiple Items!
#software development
#programming
#Structs
#JSON Array
#JSON
#Go
Go and JSON Array - Easily Manage Multiple Items!
Did you know that we can store multiple items in a JSON Array? For example, data about several people or multiple product items. In this episode, we will teach you how to use JSON Arrays in Go, from creating an Array, converting it to JSON, to easily converting the JSON Array back to use in your code!
Example of a JSON Array
Suppose we have data about a group of individuals. In JSON, we can use an Array to store data about multiple people. For instance:
In this code, we will convert a struct Array in Go to JSON and convert the JSON Array back to a struct in Go.
[
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30},
{"name": "Charlie", "age": 35}
]
Converting an Array of Structs to JSON (Encoding)
In Go, we use []struct to create an Array of Structs and use json.Marshal to convert it to JSON.
Example:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
people := []Person{
{Name: "Alice", Age: 25},
{Name: "Bob", Age: 30},
{Name: "Charlie", Age: 35},
}
jsonData, err := json.Marshal(people)
if err != nil {
fmt.Println("Error encoding JSON:", err)
return
}
fmt.Println(string(jsonData)) // แสดงผล JSON เป็น string
}
Result:
[
{"name":"Alice","age":25},
{"name":"Bob","age":30},
{"name":"Charlie","age":35}
]
Converting a JSON Array Back to an Array of Structs (Decoding)
Suppose we have JSON data that is an Array and we want to convert it back to an Array of structs in Go; we use json.Unmarshal.
Example:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
jsonData := []byte(`[
{"name":"Alice","age":25},
{"name":"Bob","age":30},
{"name":"Charlie","age":35}
]`)
var people []Person
err := json.Unmarshal(jsonData, &people)
if err != nil {
fmt.Println("Error decoding JSON:", err)
return
}
for _, person := range people {
fmt.Println(person.Name, "is", person.Age, "years old.")
}
}
Result:
Alice is 25 years old.
Bob is 30 years old.
Charlie is 35 years old.
Summary
- Use json.Marshal to convert an Array of structs to JSON.
- Use json.Unmarshal to convert a JSON Array back to an Array of structs.