To convert a Map object to JSON string in Go, you can use the json.Marshal() function and pass the map object as an argument to the function. It returns json string and an error object.
Syntax
jsonStr, err := json.Marshal(x)
Return value
If there is any error while converting, an error object will be assigned the error. If there is no error, the err object would be assigned nil, and the jsonStr contains the converted JSON string value.
Example
Here’s a basic example of how you can convert a Go map into a JSON string:
package main
import (
"encoding/json"
"fmt"
)
func main() {
// Define a map
data := map[string]string{
"name": "John",
"city": "New York",
}
// Convert map to JSON
jsonData, err := json.Marshal(data)
if err != nil {
fmt.Println(err)
return
}
// Print JSON string
fmt.Println(string(jsonData))
}
Output
{"city":"New York", "name":"John"}
Note: The order of keys in a JSON object is not guaranteed, as Go Maps do not preserve order.
Map with Integer Keys to JSON
When marshaling a map with integer keys to JSON using Go’s standard encoding/json package, you’ll encounter a behavior that might not be intuitive at first glance.
package main
import (
"encoding/json"
"fmt"
)
func main() {
// Define a map with integer keys
data := map[int]string{
1: "one",
2: "two",
3: "three",
}
// Convert map to JSON
jsonData, err := json.Marshal(data)
if err != nil {
fmt.Println(err)
return
}
// Print JSON string
fmt.Println(string(jsonData))
}
Output
{"1":"one","2":"two","3":"three"}
Nested Map to JSON
Let’s consider a nested map structure, where the outer map has string keys, and the inner maps can have various keys and values. This example will showcase a nested map with both string and integer keys.
package main
import (
"encoding/json"
"fmt"
)
func main() {
// Define a nested map
data := map[string]interface{}{
"user": map[string]string{
"name": "John",
"location": "New York",
},
"scores": map[int]int{
1: 100,
2: 85,
3: 90,
},
}
// Convert map to JSON
jsonData, err := json.Marshal(data)
if err != nil {
fmt.Println(err)
return
}
// Print JSON string
fmt.Println(string(jsonData))
}
Output
{"scores":{"1":100,"2":85,"3":90},"user":{"location":"New York","name":"John"}}
That’s it!
Related posts

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.