Attempting to use a custom MarshalJSON
to avoid escaping characters like &
. It's inconvenient to use a custom encoder with the SetEscapeHTML
option set in this particular case.
The function is called, and behaves as I expected. However the end result still contains the escaped form \u0026
.
https://play.golang.org/p/aktPndOUmth
package main
import (
"bytes"
"encoding/json"
"fmt"
)
type Data struct {
URL string
}
func (d Data) MarshalJSON() ([]byte, error) {
data := map[string]interface{}{
"url": d.URL,
}
jsonData, _ := json.Marshal(data)
jsonData = bytes.Replace(jsonData, []byte("\\u0026"), []byte("&"), -1)
fmt.Println("func: " + string(jsonData))
return jsonData, nil
}
func main() {
data := Data{
URL: "https://test.com?foo=1&bar=2",
}
jsonData, _ := json.Marshal(data)
fmt.Println("main: " + string(jsonData))
}
Output:
func: {"url":"https://test.com?foo=1&bar=2"}
main: {"url":"https://test.com?foo=1\u0026bar=2"}