检测无效的 JSON 字符的最佳方法是什么?

huangapple go评论75阅读模式
英文:

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

问题

检测一个Go字符串中是否包含在JSON字符串中无效的字符,最好且最高效的方法是什么?换句话说,与这个Java问题的答案相比,Go语言中的等效方法是什么?是否只需使用strings.ContainsAny(假设ASCII控制字符)?

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("包含控制字符")
}
英文:

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

答案1

得分: 2

如果你想识别控制字符(就像你指向的Java问题的答案中所提到的),你可以使用unicode.IsControl来获得一个更简单的解决方案。

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

英文:

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

huangapple
  • 本文由 发表于 2017年9月12日 22:45:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/46179431.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定