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\"}"
strconv.Quote()
like this:fmt.Println("MyStruct:", strconv.Quote(string(r)))
, or use the%q
verb:fmt.Printf("MyStruct: %q", r)
. Try it here: go.dev/play/p/8t4Tw0RRJhi