1

What's the best, most efficient way to detect whether a Go string contains characters that are invalid in JSON strings? In other words, what's the Go equivalent to this answer to this Java question? Is it just to use strings.ContainsAny (assuming the ASCII control characters)?

ctlChars := string([]byte{
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
    19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 127,
})
if strings.ContainsAny(str, ctlChars) {
    println("has control chars")
}
theory
  • 9,178
  • 10
  • 59
  • 129
  • 4
    Efficient in what sense? Fast? Lowest power consumption? Least number of CPU instructions? Runs on Nacl? Least duration/Watt? Least number of cache misses? Easy to understand? Most efficient during debugging? Easiest to change of the JSON spec changes? – Volker Sep 12 '17 at 14:51
  • @Volker Yes. Would be useful to know/see/document all the options and tradeoffs. – theory Sep 12 '17 at 14:53
  • "All the options and tradeoffs" is pretty broad. If you have a particular optimization target that might be narrow enough to answer on SO. – Adrian Sep 12 '17 at 15:02

1 Answers1

2

If you are looking to identify control characters (as in the answers to the Java question you pointed to), you might want to use unicode.IsControl for a simpler solution.

https://golang.org/pkg/unicode/#IsControl

func containsControlChar(s string) bool {
    for _, c := range s {
        if unicode.IsControl(c) {
            return true
        }
    }
    return false
}

Playground: https://play.golang.org/p/Pr_9mmt-th

eugenioy
  • 11,825
  • 28
  • 35