Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you escape characters within a string (JSON format)

Tags:

json

escaping

go

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])
}
like image 873
Jay Avatar asked Aug 05 '18 06:08

Jay


People also ask

How do I escape characters in a string?

To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split('').

How do I add an escape character to a JSON string in Java?

You can escape String in Java by putting a backslash in double quotes e.g. " can be escaped as \" if it occurs inside String itself. This is ok for a small JSON String but manually replacing each double quote with an escape character for even a medium-size JSON is time taking, boring, and error-prone.

Do I need to escape ampersand in JSON?

Certain characters need to be "escaped" when used as part of JSON, like an ampersand (&). You can manually escape these characters, buta better route is to use the ConvertTo-Json cmdlet.

How do you escape a line break in JSON?

JSON strings do not allow real newlines in its data; it can only have escaped newlines. Snowflake allows escaping the newline character by the use of an additional backslash character.


1 Answers

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.

like image 176
nbari Avatar answered Oct 10 '22 17:10

nbari