• golang json.Marshal 特殊html字符被转义的解决方法


    go语言提供了json的编解码包,json字符串作为参数值传输时发现,json.Marshal生成json特殊字符<、>、&会被转义。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    type Test struct {
      Content   string
    }
    func main() {
      t := new(Test)
      jsonByte, _ := json.Marshal(t)
      fmt.Println(string(jsonByte))
    }
    1
    2
    {"Content":"http://www.baidu.com?id=123u0026test=1"}
    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,会转义 <、>、&

    1
    2
    3
    4
    5
    6
    7
    8
    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
    }

    解决方案

    方法一:

    1
    2
    3
    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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    type Test struct {
      Content   string
    }
    func main() {
      t := new(Test)
      bf := bytes.NewBuffer([]byte{})
      jsonEncoder := json.NewEncoder(bf)
      jsonEncoder.SetEscapeHTML(false)
      jsonEncoder.Encode(t)
      fmt.Println(bf.String())
    }
    1
    2
    Process finished with exit code 0

    查看文档和源码还是解决问题的好方法。

  • 相关阅读:
    稀疏自编码器和矢量化编程
    使用支持向量机训练mnist数据
    采用libsvm进行mnist训练
    支持向量机
    月下“毛景树”
    最小费用最大流模板
    最大流模板
    选学霸
    线段树 2
    线段树 1
  • 原文地址:https://www.cnblogs.com/jiftle/p/14960002.html
Copyright © 2020-2023  润新知