how to convert map to string in golang?
September 07, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
To convert map to string in golang,
- First convert it JSON using
json.Marshal()
method - 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.
https://aguidehub.com/blog/how-to-install-golang-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
main.go
package main
import (
"fmt"
"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 {
fmt.Println(err.Error())
return
}
jsonStr := string(userData)
fmt.Println(jsonStr)
}
In the above example, we have converted the map to string and printed in golang console. let’s check the output.
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 👍.