教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 golang中json.marshal字符转义问题

golang中json.marshal字符转义问题

发布时间:2022-01-18   编辑:jiaochengji.com
教程集为您提供golang中json.marshal字符转义问题等资源,欢迎您收藏本站,我们将为您提供最新的golang中json.marshal字符转义问题资源
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;"><path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"/></svg>

最近在封装自定义json库,数据结构用自带的map,序列化接口调用了json.marshal去实现,发现&字符序列化之后变成了\u0026。

<h1>1、查阅了godoc文档,解释如下:</h1>

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) called on it.

也就是说json.marshal默认escapeHtml为true,会将<、>、&等字符转义。

<h2>
godoc打开方式可参考如下:</h2>

1、直接在CMD下,运行godoc -http=:8080就可以了;
2、然后再浏览器上输入127.0.0.1:8080就可以访问本地的GO DOC文档库;

<h1>
2、解决方案</h1> <pre><code>package main import ( "bytes" "encoding/json" "fmt" ) type MarshalTest struct { Url string `json:"url"` } //序列化 func marshal_inner(data interface{}) ([]byte, error) { bf := bytes.NewBuffer([]byte{}) jsonEncoder := json.NewEncoder(bf) jsonEncoder.SetEscapeHTML(false) if err := jsonEncoder.Encode(data); err != nil { return nil, err } return bf.Bytes(), nil } func main() { t := &MarshalTest{ Url: "http://www.baidu.com?seq=213&uuid=1", } val, err := marshal_inner(t) if err != nil { fmt.Println("marshal_inner failed.err:", err) return } fmt.Println("marshal_inner val:", string(val)) } </code></pre> 到此这篇关于“golang中json.marshal字符转义问题”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
golang中json.marshal字符转义问题
golang 自定义json解析
Go 学习笔记 09 | Golang 结构体与 JSON 互相转换
golang结构体tag的使用
golang 结构体struct 标签tag 简介
golang json忽略解析字段的两个方法 (golang json 序列化含有父节点指针的结构体时电脑跑满内存卡死)
Go语言中struct内部的反引号
活学活用golang的反射机制
go 语言 生成json字符串数组
golang 踩坑

[关闭]
~ ~