How to Convert “1:2,3:4” to map[int]int in Go

Kacper Bąk
2 min readMar 11, 2023
Photo by Eugene Chystiakov on Unsplash

While working on a project in Go that requires sending data from the frontend to the backend, I encountered a situation where the frontend sends data in a different format than the backend expects. The backend expects the type map[int]int to store category sizes, but the frontend sends data in the format “1:2,3:4”. In this article, I will show how to convert “1:2,3:4” to map[int]int in Go.

First, I will define the CategorySizes structure as an alias for the map[int]int type:

type CategorySizes map[int]int

I will then define two methods: MarshalJSON and UnmarshalJSON. The MarshalJSON method converts a map to a string, and then serializes it to JSON. The UnmarshalJSON method deserializes JSON to a string, converts the string to a map, and then assigns it to the CategorySizes variable.

func (c CategorySizes) MarshalJSON() ([]byte, error) {
var parts []string
for k, v := range c {
parts = append(parts, fmt.Sprintf("%d:%d", k, v))
}
return json.Marshal(strings.Join(parts, ","))
}
func (c *CategorySizes) UnmarshalJSON(data []byte) error {
var input string
if err := json.Unmarshal(data, &input); err != nil {
return err
}

result := make(map[int]int)
pairs := strings.Split(input, ",")
for _, pair := range pairs {
parts := strings.Split(pair, ":")
if len(parts) == 2 {
key, err1 := strconv.Atoi(parts[0])
value, err2 := strconv.Atoi(parts[1])
if err1 == nil && err2 == nil {
result[key] = value
}
}
}
*c = result
return nil
}

In the main function, I will show how to use CategorySizes variables to marshal and unmarshal data. To marshal the data, I first parsed the input data “1:2,3:4” into a map, and then used the json.Marshal function to convert it to JSON. To retrieve the data, I parsed the JSON input data back into the map using the json.Unmarshal function.

func main() {
input := "1:2,3:4"

// Marshal
categorySizes := make(CategorySizes)
pairs := strings.Split(input, ",")
for _, pair := range pairs {
parts := strings.Split(pair, ":")
if len(parts) == 2 {
key, _ := strconv.Atoi(parts[0])
value, _ := strconv.Atoi(parts[1])
categorySizes[key] = value
}
}
jsonBytes, _ := json.Marshal(categorySizes)
fmt.Println(string(jsonBytes))

// Unmarshal
var unmarshaled CategorySizes
json.Unmarshal(jsonBytes, &unmarshaled)
fmt.Println(unmarshaled)
}

After running the program, I received the following data in the output:

"1:2,3:4"
map[1:2 3:4]

The first output is the serialized JSON, and the second output is the deserialized CategorySizes map.

In conclusion, converting “1:2,3:4” to map[int]int in Go is a relatively simple process.

--

--