Marshaling and unmarshaling a map to/from JSON in Go can be done using the encoding/json
package.
Here's an example of how you can marshal a map to JSON:
package main
import (
"encoding/json"
"fmt"
)
func main() {
data := map[string]interface{}{
"name": "John Doe",
"age": 30,
"active": true,
}
jsonData, err := json.Marshal(data)
if err != nil {
fmt.Println("Error marshaling JSON:", err)
return
}
fmt.Println(string(jsonData))
}
In the above example, we have a map called data
which contains key-value pairs of various data types. We use json.Marshal()
to marshal the map to JSON. The resulting JSON data is stored in the jsonData
variable, which is then printed.
To unmarshal JSON back into a map, you can use the following example:
package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonData := []byte(`{"name":"John Doe","age":30,"active":true}`)
var data map[string]interface{}
err := json.Unmarshal(jsonData, &data)
if err != nil {
fmt.Println("Error unmarshaling JSON:", err)
return
}
fmt.Println(data)
}
In this example, we have the JSON data stored in the jsonData
variable. We declare a map variable called data
, and then use json.Unmarshal()
to unmarshal the JSON data into the map. The resulting map is printed to the console.
Note that in both examples, we use a map with string keys and interface{}
values to support different data types. Change the types in the example according to your specific needs.