Home >Backend Development >Golang >How to Prevent `` Escaping During JSON Marshaling in Go?

How to Prevent `` Escaping During JSON Marshaling in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-12-21 10:33:14376browse

How to Prevent `` Escaping During JSON Marshaling in Go?

Overcoming Encoding Obstacles: Suppressing < and > Escaping in json.Marshal

Introduction

When dealing with data in JSON format, it is sometimes necessary to retain certain characters, such as < and >, as part of the encoded string. However, json.Marshal, the default Go library function for converting objects to JSON strings, automatically escapes these characters to prevent potential security vulnerabilities. This can be problematic when the data contains HTML or XML code, which relies on these characters.

Problem

In the following code snippet, the XmlRequest field contains HTML-like content, but after json.Marshal encoding, the < and > characters are escaped:

package main

import (
    "encoding/json"
    "fmt"
)

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

func main() {
    track := new(Track)
    track.XmlRequest = "<car><mirror>XML</mirror></car>"
    trackJSON, _ := json.Marshal(track)
    fmt.Println("After Marshal:", string(trackJSON))
}

The resulting JSON string is:

{"xmlRequest":"\u003ccar\u003e\u003cmirror\u003eXML\u003c/mirror\u003e\u003c/car\u003e"}

The desired JSON string, however, would be:

{"xmlRequest":"<car><mirror>XML</mirror></car>"}

Solution

As of Go 1.7, there is no built-in mechanism within json.Marshal to disable escaping. However, a workaround is to create a custom function that explicitly controls the escaping behavior.

func (t *Track) JSON() ([]byte, error) {
    buffer := new(bytes.Buffer)
    encoder := json.NewEncoder(buffer)
    encoder.SetEscapeHTML(false)
    if err := encoder.Encode(t); err != nil {
        return nil, err
    }
    return buffer.Bytes(), nil
}

In this custom JSON() method, the encoder's SetEscapeHTML flag is set to false, disabling HTML character escaping. By calling this method instead of json.Marshal, the original content can be preserved without escaping:

trackJSON, err := track.JSON()

Alternatively, a more generic solution can be implemented by creating a function that takes any interface{} as input:

func JSONMarshal(v interface{}) ([]byte, error) {
    buffer := new(bytes.Buffer)
    encoder := json.NewEncoder(buffer)
    encoder.SetEscapeHTML(false)
    if err := encoder.Encode(v); err != nil {
        return nil, err
    }
    return buffer.Bytes(), nil
}

The above is the detailed content of How to Prevent `` Escaping During JSON Marshaling in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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