To convert a map to a JSON string in Go, you can use the json.Marshal
function from the encoding/json
package. This function converts a Go map into a JSON-encoded byte slice, which you can then convert to a string.
We can convert a map to a JSON string in Go using the json.Marshal
function from the encoding/json
package.
For example,
encoding/json
and fmt
packages.myMap
with key-value pairs.json.Marshal
function.fmt.Println
function.package main
import (
"encoding/json"
"fmt"
)
func main() {
// Declare and initialize a map
myMap := map[int]int{
1: 10,
2: 20,
3: 30,
4: 40,
5: 50,
}
// Convert the map to a JSON-encoded byte slice
jsonBytes, err := json.Marshal(myMap)
if err != nil {
fmt.Println(err)
return
}
// Convert the byte slice to a string
jsonString := string(jsonBytes)
// Print the resulting JSON string
fmt.Println("JSON string from map:", jsonString)
}
JSON string from map: {"1":10,"2":20,"3":30,"4":40,"5":50}
In this tutorial, we learned How to Convert a Map to a JSON String in Go language with well detailed examples.