如何在HTML标签中转换转义字符?

时间:2016-04-10 10:26:24

标签: html string go escaping html-escape-characters

我们如何直接将"\u003chtml\u003e"转换为"<html>"?使用"<html>""\u003chtml\u003e"转换为json.Marshal()非常简单,但json.Unmarshal()非常冗长且繁琐。在golang中有没有直接的方法呢?

2 个答案:

答案 0 :(得分:3)

您可以使用strconv.Unquote()进行转换。

您应该注意的一点是strconv.Unquote()只能取消引号中的字符串(例如,引号char "或后引号char `的开头和结尾) ,所以我们必须手动追加。

示例:

// 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())不会解码\uxxxx形式的unicode序列,只能解码&#decimal;&#xHH;

示例:

fmt.Println(html.UnescapeString(`\u003chtml\u003e`)) // wrong
fmt.Println(html.UnescapeString(`&#60;html&#62;`))   // good
fmt.Println(html.UnescapeString(`&#x3c;html&#x3e;`)) // 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

答案 1 :(得分:0)

我认为这是一个普遍的问题。这就是我的工作方式。

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-

希望这对某人有帮助。

相关问题