DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

Go - Unicode characters to Unicode escape sequence

#go

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

Top comments (0)