Home > Net >  Replace characters in go serialization by using custom MarshalJSON method
Replace characters in go serialization by using custom MarshalJSON method

Time:06-17

As far as I saw, I just did a customized MarshalJSON method in order to replace these characters:\u003c and \u003e: https://go.dev/play/p/xJ-qcMN9QXl

In 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 :)

CodePudding user response:

In the Marshal 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:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
)

type Foo struct {
    Name    string
    Surname string
    Likes   map[string]interface{}
    Hates   map[string]interface{}
    newGuy  bool //rpcclonable
}

func main() {
    foo := &Foo{
        Name:    "George",
        Surname: "Denkin",
        Likes: map[string]interface{}{
            "Sports":  "volleyball",
            "Message": "<Geroge> play volleyball <usually>",
        },
    }
    buf := &bytes.Buffer{} // or &strings.Builder{} as from the example of @mkopriva
    enc := json.NewEncoder(buf)
    enc.SetEscapeHTML(false)
    err := enc.Encode(foo)
    if err != nil {
        return
    }
    fmt.Println(buf.String())
}
  • Related