doujiao2000
2018-08-05 06:20
浏览 2.1k

如何在golang中的字符串(JSON格式)中转义字符

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? https://play.golang.org/p/rcHZbrjFyyH

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 {
        panic(err)
    }
    // Trim the beginning and trailing " character
    return string(b[1:len(b)-1])
}

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

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

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

这行得通,但是肯定有一种更惯用的方式吗? https://play.golang.org/p/rcHZbrjFyyH

  func main(){
 fmt.Println  (jsonEscape(`dog“ fish” cat`))
 //输出:dog \“ fish \” cat 
} 
 
func jsonEscape(i string)string {
b,err:= json.Marshal(i  )
 if err!= nil {
 panic(err)
} 
 //修剪开头和结尾的“ character 
 return string(b [1:len(b)-1])
} \  n   
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douweilaton2762 2018-08-05 10:16
    已采纳

    I don't know if using backticks ` is the most idiomatic way to escape characters but is more readable, for example, you could use something like:

    fmt.Println(jsonEscape(`dog "fish" cat`))
    

    https://play.golang.org/p/khG7qBROaIx

    Check the String literals section.

    点赞 打赏 评论

相关推荐 更多相似问题