英文:
How to print struct as a plain string with escape characters in golang?
问题
我正在尝试将一个 Golang 结构体作为带有转义字符的字符串打印出来,但是无法实现。
我想要像这样打印我的结构体:
"{\"data\":\"MyName\",\"value\":\"Ashutosh\"}"
这是我尝试过的代码:
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))
}
但是它打印出来的结果是这样的:
{"data":"Name","value":"Ashutosh"}
有人可以帮助我得到以下输出吗?
"{\"data\":\"MyName\",\"value\":\"Ashutosh\"}"
英文:
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\"}"
答案1
得分: 2
要引用任何字符串,你可以使用strconv.Quote()
函数:
fmt.Println("MyStruct:", strconv.Quote(string(r)))
在fmt
包中还有一个用于引用字符串的动词:%q:
字符串和字节切片(这些动词等效对待):
%q
:一个使用Go语法安全转义的双引号字符串
所以你也可以这样打印:
fmt.Printf("MyStruct: %q", string(r))
由于这也适用于字节切片,所以你甚至不需要进行string
转换:
fmt.Printf("MyStruct: %q", r)
这些都会输出以下结果(在Go Playground上尝试一下):
MyStruct: "{\"data\":\"Name\",\"value\":\"Ashutosh\"}"
英文:
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\"}"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论