Conversion between golang map and string

Convert map and json to each other

MapToJson is map to json. JsonToMap is json is map

package main
import (
    "encoding/json"
    "fmt"
)
func MapToJson(param map[string]interface{}) string {
    //json转map
    dataType, _ := json.Marshal(param)
    dataString := string(dataType)
    return dataString
}
func JsonToMap(str string) map[string]interface{} {
    //map 转json
    var tempMap map[string]interface{}
    err := json.Unmarshal([]byte(str), &tempMap)
    if err != nil {
        panic(err)
    }
    return tempMap
}
func main() {
    params := make(map[string]interface{})
    params["name"] = "test"
    params["domain"] = "https://www.baidu.com?name=1&id=1"
    parmJson := MapToJson(params)
    fmt.Println("parmJson:", parmJson)
    parmMap := JsonToMap(parmJson)
    fmt.Println("parmMap:", parmMap)
}

Leave a Reply

Your email address will not be published.

en_USEnglish