GolangJson Marshal UN-Escape Unicode Characters/解决go的Marshal的转义和格式化输出

GoLang Escape characters for Json fomat

前言

GoLang 将结构体struct进行Marshal后,会将HTML中的<span></span>等以Unicode形式输出,如下形式:第一行代码是Marshal后的输出,但是有时候需要的是原格式的json,但是Golang中没有PythonDecode的功能,需要使用者自己转化。

"\u003cspan\u003e\u003cfont color=\"black\"\u003ehand-rolled \u003c/font\u003e\u003c/span\u003e"

<span><font color=\"black\">hand-rolled </font></span>

本文主要解决两个问题:
1、go json的反转义Unicode,以原格式输出;
2、go jsonFormation形式输出。

go-json 反转义(1)

该方法是通过将marshal后的json文本进行对应的转义替换成原有格式,只要采用strconv.Quotestrconv.Unquotestrings.Replace三个方法, 具体使用看源代码

源代码

// Quote returns a double-quoted Go string literal representing s. The
// returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for
// control characters and non-printable characters as defined by
// IsPrint.
func Quote(s string) string {
   
	return quoteWith(s, '"', false, false)
}
func quoteWith(s string, quote byte, ASCIIonly, graphicOnly bool) string {
   
	return string(appendQuotedWith(make([]byte, 0, 3*len(s)/2), s, quote, ASCIIonly, graphicOnly))
}
func appendQuotedWith(buf []byte, s string, quote byte, ASCIIonly, graphicOnly bool) []byte {
   
	// Often called with big strings, so preallocate. If there's quoting,
	// this is conservative but still helps a lot.
	if cap(buf)-len(buf) < len(s) {
   
		nBuf := make([]byte, len(buf), len(buf)+1+len(s)+1)
		copy(nBuf, buf)
		buf = nBuf
	}
	buf = append(buf, quote)
	for width := 0; len(s) > 0; s = s[width:] {
   
		r := rune(s[0])
		width = 1
		if r >= utf8.RuneSelf {
   
			r, width = utf8.DecodeRuneInString(s)
		}
		if width == 1 && r == utf8.RuneError {
   
			buf = append(buf, `\x`...)
			buf = append(buf, lowerhex[s[0]>>4])
			buf = append(buf, lowerhex[s[0]&0xF])
			continue
		}
		buf = appendEscapedRune(buf, r, quote, ASCIIonly, graphicOnly)
	}
	buf = append(buf, quote)
	return buf
}

// Unquote interprets s as a single-quoted, double-quoted,
// or backquoted Go string literal, returning the string value
// that s quotes.  (If s is single-quoted, it would be a Go
// character literal; Unquote returns the corresponding
// one-character string.)
func Unquote(s string) (string, error) {
   
	n := len(s)
	if n < 2 {
   
		return "", ErrSyntax
	}
	quote := s[0]
	if quote != s[n-1] {
   
		return "", ErrSyntax
	}
	s = s[1 : n-1]

	if quote == '`' {
   
		if contains(s, '`') {
   
			return "", ErrSyntax
		}
		if contains(s, '\r') {
   
			// -1 because we know there is at least one \r to remove.
			buf := make([]byte, 0, len(s)-1)
			for i :=</
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值