给出以下示例:
func main() {
buf := new(bytes.Buffer)
enc := json.NewEncoder(buf)
toEncode := []string{"hello", "wörld"}
enc.Encode(toEncode)
fmt.Println(buf.String())
}
我想用转义的Unicode字符显示输出:
[“ hello”,“ w \ u00f6rld”]
而不是:
[“你好”,“世界”]
我试图编写一个使用strconv.QuoteToASCII
引用Unicode字符并将其输入到Encode()
的函数,但这会导致两次转义:
func quotedUnicode(data []string) []string {
for index, element := range data {
quotedUnicode := strconv.QuoteToASCII(element)
// get rid of additional quotes
quotedUnicode = strings.TrimSuffix(quotedUnicode, "\"")
quotedUnicode = strings.TrimPrefix(quotedUnicode, "\"")
data[index] = quotedUnicode
}
return data
}
[“ hello”,“ w \\ u00f6rld”]
如何确保json.Encode的输出包含正确转义的Unicode字符?