3 回答

TA貢獻1998條經驗 獲得超6個贊
您可以使用strconv.Unquote()來進行轉換。
您應該注意的一件事是,strconv.Unquote()只能取消引號中的字符串(例如,以引號字符"或反引號字符開頭和結尾`),因此我們必須手動附加它。
例子:
// Important to use backtick ` (raw string literal)
// else the compiler will unquote it (interpreted string literal)!
s := `\u003chtml\u003e`
fmt.Println(s)
s2, err := strconv.Unquote(`"` + s + `"`)
if err != nil {
panic(err)
}
fmt.Println(s2)
輸出(在Go Playground上試試):
\u003chtml\u003e
<html>
注意:要進行 HTML 文本轉義和反轉義,您可以使用html包。引用它的文檔:
包 html 提供轉義和取消轉義 HTML 文本的功能。
但是html包(特別是html.UnescapeString())不解碼形式的 unicode 序列\uxxxx,只有&#decimal;或&#xHH;。
例子:
fmt.Println(html.UnescapeString(`\u003chtml\u003e`)) // wrong
fmt.Println(html.UnescapeString(`<html>`)) // good
fmt.Println(html.UnescapeString(`<html>`)) // good
輸出(在Go Playground上試試):
\u003chtml\u003e
<html>
<html>
筆記2:
您還應該注意,如果您編寫這樣的代碼:
s := "\u003chtml\u003e"
這個帶引號的字符串將被編譯器本身取消引用,因為它是一個解釋過的字符串文字,所以你不能真正測試它。要在源代碼中指定帶引號的字符串,您可以使用反引號來指定原始字符串文字,或者您可以使用雙引號解釋的字符串文字:
s := "\u003chtml\u003e" // Interpreted string literal (unquoted by the compiler!)
fmt.Println(s)
s2 := `\u003chtml\u003e` // Raw string literal (no unquoting will take place)
fmt.Println(s2)
s3 := "\\u003chtml\\u003e" // Double quoted interpreted string literal
// (unquoted by the compiler to be "single" quoted)
fmt.Println(s3)
輸出:
<html>
\u003chtml\u003e

TA貢獻1802條經驗 獲得超5個贊
我認為這是一個普遍的問題。這就是我讓它工作的方式。
func _UnescapeUnicodeCharactersInJSON(_jsonRaw json.RawMessage) (json.RawMessage, error) {
str, err := strconv.Unquote(strings.Replace(strconv.Quote(string(_jsonRaw)), `\\u`, `\u`, -1))
if err != nil {
return nil, err
}
return []byte(str), nil
}
func main() {
// Both are valid JSON.
var jsonRawEscaped json.RawMessage // json raw with escaped unicode chars
var jsonRawUnescaped json.RawMessage // json raw with unescaped unicode chars
// '\u263a' == '?'
jsonRawEscaped = []byte(`{"HelloWorld": "\uC548\uB155, \uC138\uC0C1(\u4E16\u4E0A). \u263a"}`) // "\\u263a"
jsonRawUnescaped, _ = _UnescapeUnicodeCharactersInJSON(jsonRawEscaped) // "?"
fmt.Println(string(jsonRawEscaped)) // {"HelloWorld": "\uC548\uB155, \uC138\uC0C1(\u4E16\u4E0A). \u263a"}
fmt.Println(string(jsonRawUnescaped)) // {"HelloWorld": "??, ??(世上). ?"}
}
https://play.golang.org/p/pUsrzrrcDG-
希望這可以幫助某人。

TA貢獻1850條經驗 獲得超11個贊
您可以fmt
為此范圍使用字符串格式化包。
fmt.Printf("%v","\u003chtml\u003e") // will output <html>
https://play.golang.org/p/ZEot6bxO1H
- 3 回答
- 0 關注
- 603 瀏覽
添加回答
舉報