how to convert map to string in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To convert map to string in golang,

  1. First convert it JSON using json.Marshal() method
  2. Then convert JSON to JSON string using string() method

it will convert map to string. just you have to covert to MAP to JSON and then JSON to string.

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

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

To use the json.Marshal() method, we have first import "encoding/json" package, then we have to create json variable which we will use to assign value.

Let’s start our Golang convert map to string example


package main

import (
	"encoding/json"	// Encoding and Decoding Package

func main() {
  	// Create a map of key/value pairs and parses the data into JSON
	user := make(map[string]interface{})
	user["id"] = 1
	user["name"] = "James Bond"
	user["phone"] = map[string]interface{}{
	"home": "123-466-799",
	"office": "564-987-654",
	user["email"] = "[email protected]"

	// Marshal the map into a JSON string.
	userData, err := json.Marshal(user)	
	if err != nil {
	jsonStr := string(userData)

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


{"email":"[email protected]","id":1,"name":"James Bond","phone":{"home":"123-466-799","office":"564-987-654"}}

I hope it helps you, All the best 👍.

Follow me on Twitter