theory
theory

Reputation: 9887

Go: What's the best way to detect invalid JSON string characters?

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")
}

Upvotes: 1

Views: 494

Answers (1)

eugenioy
eugenioy

Reputation: 12393

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

Upvotes: 2

Related Questions