golang json.Marshal 特殊html字符被转义的解决方法
go语言提供了json的编解码包,json字符串作为参数值传输时发现,json.Marshal生成json特殊字符<、>、&会被转义。
typeTeststruct{ Contentstring } funcmain(){ t:=new(Test) t.Content="http://www.baidu.com?id=123&test=1" jsonByte,_:=json.Marshal(t) fmt.Println(string(jsonByte)) }
{"Content":"http://www.baidu.com?id=123\u0026test=1"} Processfinishedwithexitcode0
GoDoc描述
StringvaluesencodeasJSONstringscoercedtovalidUTF-8,
replacinginvalidbyteswiththeUnicodereplacementrune.
Theanglebrackets“<”and“>”areescapedto“\u003c”and“\u003e”
tokeepsomebrowsersfrommisinterpretingJSONoutputasHTML.
Ampersand“&”isalsoescapedto“\u0026”forthesamereason.
ThisescapingcanbedisabledusinganEncoderthathadSetEscapeHTML(false)alledonit.
json.Marshal默认escapeHtml为true,会转义<、>、&
funcMarshal(vinterface{})([]byte,error){ e:=&encodeState{} err:=e.marshal(v,encOpts{escapeHTML:true}) iferr!=nil{ returnnil,err } returne.Bytes(),nil }
解决方案
方法一:
content=strings.Replace(content,"\\u003c","<",-1) content=strings.Replace(content,"\\u003e",">",-1) content=strings.Replace(content,"\\u0026","&",-1)
这种方式比较直接,硬性字符串替换。比较憨厚
方法二:
文档中写到ThisescapingcanbedisabledusinganEncoderthathadSetEscapeHTML(false)alledonit.
我们先创建一个buffer用于存储json
创建一个jsonencoder
设置html编码为false
typeTeststruct{ Contentstring } funcmain(){ t:=new(Test) t.Content="http://www.baidu.com?id=123&test=1" bf:=bytes.NewBuffer([]byte{}) jsonEncoder:=json.NewEncoder(bf) jsonEncoder.SetEscapeHTML(false) jsonEncoder.Encode(t) fmt.Println(bf.String()) }
{"Content":"http://www.baidu.com?id=123&test=1"} Processfinishedwithexitcode0
查看文档和源码还是解决问题的好方法。
以上这篇golangjson.Marshal特殊html字符被转义的解决方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。