go语言提供了json的编解码包,json字符串作为参数值传输时发现,json.Marshal生成json特殊字符<、>、&会被转义。
type Test struct { Content string } func main() { t := new(Test) t.Content = "http://www.baidu.com" jsonByte, _ := json.Marshal(t) fmt.Println(string(jsonByte)) }
{"Content":"http://www.baidu.com"} Process finished with exit code 0
GoDoc描述
String values encode as JSON strings coerced to valid UTF-8,
replacing invalid bytes with the Unicode replacement rune.
The angle brackets “<” and “>” are escaped to “\u003c” and “\u003e”
to keep some browsers from misinterpreting JSON output as HTML.
Ampersand “&” is also escaped to “\u0026” for the same reason.
This escaping can be disabled using an Encoder that had SetEscapeHTML(false) alled on it.
json.Marshal 默认 escapeHtml 为true,会转义 <、>、&
func Marshal(v interface{}) ([]byte, error) { e := &encodeState{} err := e.marshal(v, encOpts{escapeHTML: true}) if err != nil { return nil, err } return e.Bytes(), nil }
解决方案
方法一:
content = strings.Replace(content, "\\u003c", "<", -1) content = strings.Replace(content, "\\u003e", ">", -1) content = strings.Replace(content, "\\u0026", "&", -1)
这种方式比较直接,硬性字符串替换。比较憨厚
方法二:
文档中写到This escaping can be disabled using an Encoder that had SetEscapeHTML(false) alled on it.
我们先创建一个buffer用于存储json
创建一个jsonencoder
设置html编码为false
type Test struct { Content string } func main() { t := new(Test) t.Content = "http://www.baidu.com" bf := bytes.NewBuffer([]byte{}) jsonEncoder := json.NewEncoder(bf) jsonEncoder.SetEscapeHTML(false) jsonEncoder.Encode(t) fmt.Println(bf.String()) }
{"Content":"http://www.baidu.com"} Process finished with exit code 0
查看文档和源码还是解决问题的好方法。
以上这篇golang json.Marshal 特殊html字符被转义的解决方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 吴俊宏.2014-爱着你【豪记】【WAV+CUE】
- 名洋.1990-分手摆在胸口【天下唱片】【WAV+CUE】
- 罗大佑.2018-当年离家的年轻人巡回演唱会【大右音乐】【WAV+CUE】
- 姜育恒.1991-金曲精丫永声】【WAV+CUE】
- 水木年华.2010-启程【英皇星艺】【WAV+CUE】
- 邓丽君《漫步人生路》[DSF][1.3G]
- 林俊杰《学不会》[DSF][1.3G]
- 费玉清《Ultimate Sound》SACD 限量版[DSF][2G]
- 杨耀东.2002-经典金曲珍藏版2CD【东尼机构】【WAV+CUE】
- 新民樂演奏《春来人不来上海管弦楽團伴奏》[WAV+CUE].
- 玛吉阿米藏族民间歌舞艺术团-《仓央嘉措之歌》[ADMS][WAV+CUE]
- 王心凌《爱你》[FLAC][836M]
- 叶少菲《纯爱沉思录》[320K/MP3][120.43MB]
- 叶少菲《纯爱沉思录》[FLAC/分轨][330.3MB]
- 电子琴《汽车音响精品第三集第四集第五集》特效360度[WAV+CUE]