Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > golang中json.marshal字符转义

golang中json.marshal字符转义问题及解决

作者:灰艾凌

这篇文章主要介绍了golang中json.marshal字符转义问题及解决过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

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

1、查阅了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) called on it.

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

godoc打开方式

可参考如下:

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

2、解决方案

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))
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文