Home > Backend Development > Golang > How to Bypass HTML Character Escaping in Go's `json.Marshal`?

How to Bypass HTML Character Escaping in Go's `json.Marshal`?

Linda Hamilton
Release: 2024-12-11 14:01:10
Original
885 people have browsed it

How to Bypass HTML Character Escaping in Go's `json.Marshal`?

Bypassing HTML Character Escaping in json.Marshal

Go's json.Marshal function automatically escapes certain characters, including < and >, to prevent misinterpretation by browsers. However, this behavior can be undesirable when serializing XML data as it alters the intended content.

Unfortunately, it's not possible to disable character escaping using the json.Marshal function alone. The source code reveals that character escaping is hardcoded as true, ensuring that < and > are always converted to "u003c" and "u003e" respectively. This limitation extends to implementing custom MarshalJSON methods, as they still rely on the internal json.Marshal implementation.

To overcome this obstacle, a workaround involves defining a custom function for marshalling. Here's a modified version of your Track type that implements a JSON method:

import "bytes"
import "encoding/json"

type Track struct {
    XmlRequest string `json:"xmlRequest"`
}

func (t *Track) JSON() ([]byte, error) {
    buffer := &bytes.Buffer{}
    encoder := json.NewEncoder(buffer)
    encoder.SetEscapeHTML(false)
    err := encoder.Encode(t)
    return buffer.Bytes(), err
}
Copy after login

By using this custom JSON method, you can control the escaping behavior by explicitly setting SetEscapeHTML(false).

If you require a generic solution for any struct, you can define the following function:

import "bytes"
import "encoding/json"

func JSONMarshal(t interface{}) ([]byte, error) {
    buffer := &bytes.Buffer{}
    encoder := json.NewEncoder(buffer)
    encoder.SetEscapeHTML(false)
    err := encoder.Encode(t)
    return buffer.Bytes(), err
}
Copy after login

The above is the detailed content of How to Bypass HTML Character Escaping in Go's `json.Marshal`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template