Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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\"}"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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\"}"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading