To convert a map to string in Go, convert a map to JSON “using json.Marshal() method and then convert JSON to JSON string using the string() method.”
Using json.Marshal() function and string() method
package main
import (
"encoding/json"
"fmt"
)
func main() {
data := map[string]string{
"firstName": "John",
"lastName": "Doe",
}
jsonData, err := json.Marshal(data)
if err != nil {
fmt.Println(err)
return
}
jsonString := string(jsonData)
fmt.Println(jsonString)
}
Output
{"firstName":"John","lastName":"Doe"}
In this example:
- We define a map named data with some key-value pairs.
- We use the json.Marshal() function to convert this map to a JSON byte slice (jsonData).
- We then convert jsonData to a string (jsonString) and print it.
If you want to represent a map as a series of key=value pairs, with each pair on a new line and values surrounded by quotes, you’ll have to format the string representation of the map manually.
package main
import (
"fmt"
)
func main() {
data := map[string]string{
"firstName": "John",
"lastName": "Doe",
}
var result string
for key, value := range data {
result += fmt.Sprintf("%s=\"%s\"\n", key, value)
}
fmt.Print(result)
}
Output
firstName="John"
lastName="Doe"
Using fmt.Sprintf() method
The fmt.Sprint() function is used to convert a map to a string, but it won’t provide the exact format you have described (with each key=value pair on a new line and values surrounded by quotes). Instead, fmt.Sprint() will generate a Go-like representation of the map.
package main
import (
"fmt"
)
func main() {
data := map[string]string{
"firstName": "John",
"lastName": "Doe",
}
var result string
for key, value := range data {
result += fmt.Sprint(key, "=\"", value, "\"\n")
}
fmt.Print(result)
}
Output
firstName="John"
lastName="Doe"
That’s it!
Related posts
Go struct fields to map string

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.