To convert a JSON string to a map in Go, you can use the encoding/json package, which provides the Unmarshal function to parse JSON data into a map.
We can convert a JSON string to a map in Go by using the encoding/json package's Unmarshal function to parse the JSON string and then converting the result into a map.
For example,
encoding/json
.json.Unmarshal
function to parse the JSON string into the map.package main
import (
"encoding/json"
"fmt"
)
func main() {
// Define a JSON string
jsonString := `{"1": 10, "2": 20, "3": 30, "4": 40, "5": 50}`
// Declare an empty map to store the key-value pairs
var myMap map[string]int
// Parse the JSON string into the map
json.Unmarshal([]byte(jsonString), &myMap)
// Print the resulting map
fmt.Println("Map from JSON string:")
for key, value := range myMap {
fmt.Printf("%s: %d\n", key, value)
}
}
Map from JSON string: 1: 10 2: 20 3: 30 4: 40 5: 50
In this tutorial, we learned How to Convert a JSON String to a Map in Go language with well detailed examples.