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

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

Linda Hamilton
Release: 2024-12-21 10:33:14
Original
375 people have browsed it

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))
}
Copy after login

The resulting JSON string is:

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

The desired JSON string, however, would be:

{"xmlRequest":"<car><mirror>XML</mirror></car>"}
Copy after login

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
}
Copy after login

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()
Copy after login

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
}
Copy after login

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!

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