2018-08-05 06:20
浏览 4.2k


What is the idiomatic way to escape only the characters in a string require to be escaped by the JSON specification.

(I am not trying to marshal/unmarshal an object or string, I just want to escape the characters inside a string.

This works, but surely there is a more idiomatic way?

func main() {
    fmt.Println(jsonEscape(`dog "fish" cat`))
    //output: dog \"fish\" cat

func jsonEscape(i string) string {
    b, err := json.Marshal(i)
    if err != nil {
    // Trim the beginning and trailing " character
    return string(b[1:len(b)-1])

图片转代码服务由CSDN问答提供 功能建议

仅需对字符串中的字符进行转义的惯用方式是什么, JSON规范。</ p>

(我不想编组/解组对象或字符串,我 只是想对字符串中的字符进行转义。</ p>

这行得通,但是肯定有一种更惯用的方式吗? </ p>

  func main(){
 fmt.Println  (jsonEscape(`dog“ fish” cat`))
 //输出:dog \“ fish \” cat 
func jsonEscape(i string)string {
b,err:= json.Marshal(i  )
 if err!= nil {
 //修剪开头和结尾的“ character 
 return string(b [1:len(b)-1])
} \  n </ code> </ pre> 
 </ div>

1条回答 默认 最新

相关推荐 更多相似问题