2018-08-05 06:20
浏览 3.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规范

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


  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   
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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`))

    Check the String literals section.

    解决 无用
    打赏 举报

相关推荐 更多相似问题