Skip to content

Instantly share code, notes, and snippets.

@stokito
Created November 17, 2021 14:48
Show Gist options
  • Save stokito/43deddaa18ec309834bea175577101da to your computer and use it in GitHub Desktop.
Save stokito/43deddaa18ec309834bea175577101da to your computer and use it in GitHub Desktop.
Fast json text value encode: replace
// EncodeToJsonAsciiText Fast json text value encode: escape " with \" and \ with \\
// Any non printable or Unicode chars will be removed.
// Please note that value is not enclosed into double quotes.
func EncodeToJsonAsciiText(plain string) string {
plainLen := len(plain)
newSize := plainLen
for i := 0; i < plainLen; i++ {
c := plain[i]
if c < 32 || c > 127 { // skip non printable and unicode
newSize--
}
if c == '\\' || c == '"' {
newSize++
}
}
if plainLen == newSize {
return plain
}
encoded := make([]byte, newSize)
encodedIdx := 0
for i := 0; i < plainLen; i++ {
c := plain[i]
if c < 32 || c > 127 { // skip non printable and unicode
continue
}
if c == '\\' {
encoded[encodedIdx] = '\\'
encodedIdx++
encoded[encodedIdx] = '\\'
} else if c == '"' {
encoded[encodedIdx] = '\\'
encodedIdx++
encoded[encodedIdx] = '"'
} else {
encoded[encodedIdx] = c
}
encodedIdx++
}
return string(encoded)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment