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])
}
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('').
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With