tinthid tinthid - 1 year ago 201
JSON Question

How to return Json data without escape string in RESTful api on Golang

I have written an API with Golang. This API does receive data from other services then it responses to users in type of JSON string. Here is the problems I got.

type message struct {
Data string `json:"data"`

func test(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
data := // Retrieve message that contain backslash
json.NewEncoder(w).Encode(message{Data: data})

If there is a backslash in data that receive from other API. This API will send the response with double backslashes.


Received data:

Response data:
{"data": "asdasdasd\\asdasdasd"}

I have try to figure this out. Here what I got. All of this will be fine if I try to print out in the screen by using

I only get problem when I try to send those out put in JSON string. Therefore, is there any way to send those data without double backslashes?

Answer Source

You can create a custom method and replace double backslashes with a single one.
Something like that:

func JSONMarshal(v interface{}, backslashEscape bool) ([]byte, error) {
    b, err := json.Marshal(v)

    if backslashEscape {
        b = bytes.Replace(b, []byte('\\'), []byte('\'), -1)
    return b, err

The json/encoder packages has also DisableHTMLEscaping, if set to true, default is false, it allows you to escape HTML chars.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download