How to Serialize and Deserialize a Map in Golang

Kacper Bąk
2 min readMar 9, 2023
Photo by Annie Spratt on Unsplash

In Go, maps are a powerful data structure that allows key-value pairs to be stored dynamically. Often in my work as a backend developer, I need to serialize and deserialize a map to send it over the network, store it in a file, or send it to the front so it can do something more with it. In this article, I’ll show how to do this using the encoding/json package in Go.

I assume I have a map[int]int and I want to represent it in JSON format. The JSON structure should have a key named “categorySizes” and the value should be the map itself, where the keys represent category identifiers and the values represent their respective sizes.

To represent this JSON structure in Go, I decided to define a struct that has a field of type map[int]int:

type CategorySizes struct {
Sizes map[int]int `json:"categorySizes"`
}

In this struct, the Sizes field represents the map[int]int, and json:"categorySizes" is a tag placed on the Sizes field, which specifies how this value should be serialized and deserialized in JSON format.

Now, to convert the CategorySizes structure into JSON format, I can use the json.Marshal function from the encoding/json package, as below:

sizes := CategorySizes{
Sizes: map[int]int{
1: 10,
2: 5,
3: 20,
},
}
jsonData, err := json.Marshal(sizes)
if err != nil {
log.Fatalf("failed to marshal: %v", err)
}
fmt.Println(string(jsonData))

The expected output should be:

{"categorySizes":{"1":10,"2":5,"3":20}}

To deserialize the JSON data back into a CategorySizes structure, I can use the json.Unmarshal function, as below:

var sizes CategorySizes
if err := json.Unmarshal(jsonData, &sizes); err != nil {
log.Fatalf("failed to unmarshal: %v", err)
}
fmt.Println(sizes.Sizes)

The expected output should be:

map[1:10 2:5 3:20]

I have noticed that the order of key-value pairs can vary because Go maps are unordered.

I now assume that I want to put a CategorySizes structure inside another structure. I can do this by defining a new structure that has a field of type CategorySizes, as below:

type MyData struct {
Name string `json:"name"`
CategorySizes CategorySizes `json:"categorySizes"`
}

In this struct, the Name the field is a string and the CategorySizes the field is of type CategorySizes. The json tags on each field specify the JSON key names for each value.

To convert MyData struct to JSON format, I can use the json.Marshal function as below:

data := MyData{
Name: "Example",
CategorySizes: CategorySizes{
Sizes: map[int]int{
1: 10,
2: 5,
3: 20,
},
},
}
jsonData, err := json.Marshal(data)
if err != nil {
log.Fatalf("failed to marshal: %v", err)
}
fmt.Println(string(jsonData))

The expected output should be:

{"name":"Example","categorySizes":{"1":10,"2":5,"3":20}}

--

--