golang ES1en. Marshal Special html character escape solution

  • 2020-07-21 08:24:40
  • OfStack

go language provides the codec package of json. When the json string is transmitted as parameter value, json.Marshal generates json special characters < , > , & It gets escaped.


type Test struct {
  Content   string
}
func main() {
  t := new(Test)
  t.Content = "http://www.baidu.com?id=123&test=1"
  jsonByte, _ := json.Marshal(t)
  fmt.Println(string(jsonByte))
}

{"Content":"http://www.baidu.com?id=123\u0026test=1"}
Process finished with exit code 0

GoDoc description

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 default escapeHtml as true, will escape < , > , &


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
}

The solution

Method 1:


content = strings.Replace(content, "\\u003c", "<", -1)
content = strings.Replace(content, "\\u003e", ">", -1)
content = strings.Replace(content, "\\u0026", "&", -1)

This approach is more straightforward, hard string substitution. Relatively simple and honest

Method 2:

This escaping can disabled using an Encoder SetEscapeHTML(false) alled on it, the document says.

Let's start by creating an buffer to store json

Create 1 jsonencoder

Set html to false


type Test struct {
  Content   string
}
func main() {
  t := new(Test)
  t.Content = "http://www.baidu.com?id=123&test=1"
  bf := bytes.NewBuffer([]byte{})
  jsonEncoder := json.NewEncoder(bf)
  jsonEncoder.SetEscapeHTML(false)
  jsonEncoder.Encode(t)
  fmt.Println(bf.String())
}

{"Content":"http://www.baidu.com?id=123&test=1"}
Process finished with exit code 0

Looking at the documentation and source code is also a good way to solve the problem.


Related articles: