Go - Convert a Map type Struct to JSON

In this source code example, we show how to convert the Map to JSON in Golang with an example.

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.

Go - Convert a map to JSON - Example 1

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


package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	a := make(map[int]string)

	a[1] = "Ramesh"
	a[2] = "Raj"
	a[3] = "Umesh"

	j, err := json.Marshal(a)
	if err != nil {
		fmt.Printf("Error: %s", err.Error())
	} else {
		fmt.Println(string(j))
	}
}

Output:

{"1":"Ramesh","2":"Raj","3":"Umesh"}

Go - Convert a map to JSON - Example 2

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:


package main
import (
    "encoding/json"
    "fmt"
)
type Employee struct {
	FirstName string
	LastName string
	Email string
}

func main() {
    e := make(map[string]Employee)
    e["1"] = Employee{FirstName:"Ramesh", LastName: "Fadatare", Email: "ramesh@gmail.com"}
    j, err := json.Marshal(e)
    if err != nil {
        fmt.Printf("Error: %s", err.Error())
    } else {
        fmt.Println(string(j))
    }
}

Output:


{"1":{"FirstName":"Ramesh","LastName":"Fadatare","Email":"ramesh@gmail.com"}}

Comments