DEV Community

loading...

Go - Unicode characters to Unicode escape sequence

#go
takakd profile image Takahiro Kudo ・1 min read

Escape string in unmarshaled data.

//
func convertJsonElement(data interface{}) interface{} {
    switch v := data.(type) {
    case map[string]interface{}:
        for ik, iv := range v {
            v[ik] = convertJsonElement(iv)
        }
        data = v
    case []interface{}:
        for ik, iv := range v {
            v[ik] = convertJsonElement(iv)
        }
        data = v
    case string:
        v = fmt.Sprintf("%+q", v)
                if len(v) > 0 {
            // Remove unnecessary double-quote
            data = v[1 : len(v)-1]
                }
    default:
    }
    return data
}

//
func main() {
        jsonStr := []byte(`{"test":"こんにちは"}`)
    var data interface{}
    json.Unmarshal(jsonStr, &data)
    convertedData := convertJsonElement(data)
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide