golang——json的html标签转义问题

golang——json的html标签转义问题,第1张

json的Marshal 用来对slice,map,struct等结构化类型数据转义成[]byte/string,UnMarshal方法是用来对[]byte/string转义成指定结构的interface。但在处理html标签字符中,会存在转义问题。Marshal方法默认把html标签中的'<', '>' , '&'字符转义成unicode,为强制为有效UTF-8的JSON字符串,用Unicode替换符号替换无效字节。

go doc原文

Marshal的源码

这一行encOpts{escapeHTML: true}),这里的true导致标签被转义。

针对上述问题,有两种解决办法,第一种是替换上述三个tag,第二种是SetEscapeHtml(false);

输出:

function HTMLEncode(html) {

    var temp = document.createElement("div")

    (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html)

    var output = temp.innerHTML

    temp = null

    return output

}

var tagText = "<p><b>123&456</b></p>"

console.log(HTMLEncode(tagText))//<p><b>123&456</b></p>

function HTMLDecode(text) { 

       var temp = document.createElement("div")

        temp.innerHTML = text 

        var output = temp.innerText || temp.textContent

        temp = null 

        return output

var  tagText = "<p><b>123&456</b></p>"

var  encodeText=HTMLEncode(tagText)

console.log(encodeText)      //<p><b>123&456</b></p>

console.log(HTMLDecode(encodeText))    //<p><b>123&456</b></p>


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/6141829.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-16
下一篇 2023-03-16

发表评论

登录后才能评论

评论列表(0条)

保存