Convert map[string]interface{} to JSON string
package main
import (
"encoding/json"
"fmt"
)
func main() {
// map data
mapData := map[string]interface{}{
"Name": "noknow",
"Age": 2,
"Admin": true,
"Hobbies": []string{"IT","Travel"},
"Address": map[string]interface{}{
"PostalCode": 1111,
"Country": "Japan",
},
"Null": nil,
}
// Convert map to json string
jsonStr, err := json.Marshal(mapData)
if err != nil {
fmt.Println(err)
}
// Output
fmt.Println(string(jsonStr))
}
Convert JSON string to map[string]interface{}
package main
import (
"encoding/json"
"fmt"
)
func main() {
// json string
jsonStr := `{
"Name": "noknow",
"Age": 2,
"Admin": true,
"Hobbies": ["IT","Travel"],
"Address": {
"PostalCode": 1111,
"Country": "Japan"
},
"Null": null
}`
// Convert json string to map[string]interface{}
var mapData map[string]interface{}
if err := json.Unmarshal([]byte(jsonStr), &mapData); err != nil {
fmt.Println(err)
}
// Output
fmt.Printf("Name: %v (%T)
Age: %v (%T)
Admin: %v (%T)
Hobbies: %v (%T)
Address: %v (%T)
Null: %v (%T)
", mapData["Name"], mapData["Name"], mapData["Age"], mapData["Age"], mapData["Admin"], mapData["Admin"], mapData["Hobbies"], mapData["Hobbies"], mapData["Address"], mapData["Address"], mapData["Null"], mapData["Null"])
}