Home > Backend Development > Golang > How to Prevent JSON Escaping of '' in Go's `json.Marshal`?

How to Prevent JSON Escaping of '' in Go's `json.Marshal`?

Linda Hamilton
Release: 2024-12-16 08:41:13
Original
127 people have browsed it

How to Prevent JSON Escaping of

Preventing JSON Escaping of "<" and ">" with json.Marshal

When using json.Marshal to convert a struct into JSON, special characters like "<" and ">" are automatically escaped to their Unicode equivalents. However, there may be cases where you want these characters to be preserved in their original form.

Problem Statement

Consider the following Go program:

package main

import (
    "encoding/json"
    "fmt"
)

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

func main() {
    message := new(Track)
    message.XmlRequest = "<car><mirror>XML</mirror></car>"
    fmt.Println("Before Marshal", message)
    messageJSON, _ := json.Marshal(message)
    fmt.Println("After marshal", string(messageJSON))
}
Copy after login

Output:

Before Marshal {<car><mirror>XML</mirror></car>}
After marshal {"xmlRequest":"\u003ccar\u003e\u003cmirror\u003eXML\u003c/mirror\u003e\u003c/car\u003e"}
Copy after login

As you can see, the "<" and ">" characters have been escaped to "u003c" and "u003e" respectively.

Solution

As of Go 1.7, json.Marshal does not provide an option to disable HTML escaping. However, there is a workaround using a custom function:

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 calling this function instead of json.Marshal, you can prevent the escaping of "<" and ">".

Output:

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

The above is the detailed content of How to Prevent JSON Escaping of '' 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