how to convert map to json in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To convert map to json in golang, use the json.Marshal() method it will convert your map to JSON and return the converted JSON object.


Follow the below tutorial if you are struggling with installing GO in windows.

https://aguidehub.com/blog/how-to-install-golang-in-windows/


Today, I will show you how do I convert a map to json in golang, as above mentioned I’m going to use the json.Marshal() method.

To use the json.Marshal() method, we have first import "encoding/json" package which is built in provided by golang, then we have to pass our map with an assignable variable in json.Marshal() method.

Let’s start our Golang convert map to json example

main.go

package main

import (
    "encoding/json"
    "fmt"
)

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

    a[1] = "aGuideHub"
    a[2] = "sortoutcode"
    a[3] = "Infinitbility"

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

In the above example, we have converted a map to json and printed it in the console. let’s check the output.

Output

{"1":"aGuideHub","2":"sortoutcode","3":"Infinitbility"}

Try it Yourself

I hope it helps you, All the best 👍.

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts