DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

2 1

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)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay