Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Convert a map to JSON in Go (Golang)

Posted on January 17, 2023January 17, 2023 by admin

Table of Contents

  • Overview
  • Example

Overview

encoding/json package provides utilities that can be used to convert to and from JSON. The same utility can be used to convert a golang map to JSON string and vice versa. A very important point to note though is that map allows integer values for keys while JSON doesn’t allow integer values for keys. JSON only allows string value for keys. So a map having an integer value for the key when converted to JSON will have a string value for the key.

Example

Let’s see a program for conversion of the map to JSON

package main
import (
"encoding/json"
"fmt"
)
func main() {
a := make(map[int]string)
a[1] = "John"
j, err := json.Marshal(a)
if err != nil {
fmt.Printf("Error: %s", err.Error())
} else {
fmt.Println(string(j))
}
}

Output

{"1":"John"}

In the above code, we are using json.Marshal function to convert the map to JSON. The map has an integer value for the key.

a := make(map[int]string)

While after converting, the resultant JSON as a string value for the key

{"1":"John"}

Let’s see one more example where we convert a map to a JSON where we have a struct for the value in the map. Below is the code for that

package main
import (
"encoding/json"
"fmt"
)
type employee struct {
Name string
}
func main() {
a := make(map[string]employee)
a["1"] = employee{Name: "John"}
j, err := json.Marshal(a)
if err != nil {
fmt.Printf("Error: %s", err.Error())
} else {
fmt.Println(string(j))
}
}

Output

{"1":{"Name":"John"}}
  • go
  • golang
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP