Question:
As far as I saw, I just did a customizedMarshalJSON
method in order to replace these characters:\u003c
and \u003e
: https://go.dev/play/p/xJ-qcMN9QXlIn the example above, i marshaled the similar struct by sending to marshal from an aux struct that contains the same fields and last step is to replace the fields that I actually need and the return. As you can see in the print placed before returning from
MarshalJSON
method, the special characters were replaced, but after calling the json.Marshal
func, the special characters remains the same.Something I’m missing here but cannot figure it out. Appreciate your help. Thankies ๐
Answer:
In theMarshal
documentation of the json package https://pkg.go.dev/encoding/json#Marshal you will find the following paragraph:String values encode as JSON strings coerced to valid UTF-8, replacing invalid bytes with the Unicode replacement rune. So that the JSON will be safe to embed inside HTML tags, the string is encoded using HTMLEscape, which replaces "<", ">", "&", U+2028, and U+2029 are escaped to "\u003c","\u003e", "\u0026", "\u2028", and "\u2029". This replacement can be disabled when using an Encoder, by calling SetEscapeHTML(false).
So try it using a
Encoder
, example:If you have better answer, please add a comment about this, thank you!