14

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])
}
4
  • 1
    A slight improvement is to return string(b[1:len(b)-1]). This reduces memory allocated by two bytes. Otherwise, marshaling is the way to encoded form of a string (or any other value). Commented Aug 5, 2018 at 6:36
  • try HTMLEscape maybe? golang.org/pkg/encoding/json/#HTMLEscape Commented Aug 5, 2018 at 7:37
  • 1
    You can simply copy what is used inside the json package to do the job. golang.org/src/encoding/json/encode.go#L876 It's around line 876. If you discount for unicodes, it's basically just a switch. Commented Aug 5, 2018 at 9:38
  • The json.HTMLEscape escapes additional characters with the purpose of making JSON safe for embedding into HTML. JSON only needs ", backslash, and control characters escaped. json.org Commented Aug 19, 2018 at 22:06

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.