Go:检测无效 JSON 字符串字符的最佳方法是什么?
Go: What's the best way to detect invalid JSON string characters?
检测 Go 字符串是否包含 JSON 字符串中无效字符的最好、最有效的方法是什么?换句话说,这个 Java question 的答案等价于 Go 是什么?是否只是为了使用
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")
}
如果您想要识别控制字符(如您所指的 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
}
检测 Go 字符串是否包含 JSON 字符串中无效字符的最好、最有效的方法是什么?换句话说,这个 Java question 的答案等价于 Go 是什么?是否只是为了使用 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")
}
如果您想要识别控制字符(如您所指的 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
}