How to print struct as a plain string with escape characters in golang?

I am trying to print a Golang struct as a string with escape characters, but not able to do that.

I want to print my struct like this:

"{\"data\":\"MyName\",\"value\":\"Ashutosh\"}"

Here is what I have tried.

package main

import (
    "encoding/json"
    "fmt"
)

type Resp struct {
    Data  string `json:"data"`
    Value string `json:"value"`
}

func main() {

    var data Resp
    data.Data = "Name"
    data.Value = "Ashutosh"

    r, _ := json.Marshal(data)
    fmt.Println("MyStruct: ", string(r))

}

But it is printing like this.

{"data":"Name","value":"Ashutosh"}

Can someone help me to get the following output? :

"{\"data\":\"MyName\",\"value\":\"Ashutosh\"}"

>Solution :

To quote any strings, you may use strconv.Quote():

fmt.Println("MyStruct:", strconv.Quote(string(r)))

There’s also a verb for quoting strings in the fmt package: %q:

String and slice of bytes (treated equivalently with these verbs):

%q    a double-quoted string safely escaped with Go syntax

So you may also print it like this:

fmt.Printf("MyStruct: %q", string(r))

Since this also works for byte slices, you don’t even need the string conversion:

fmt.Printf("MyStruct: %q", r)

These all output (try it on the Go Playground):

MyStruct: "{\"data\":\"Name\",\"value\":\"Ashutosh\"}"

Leave a Reply