繁体   English   中英

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

[英]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("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
}

游乐场: https : //play.golang.org/p/Pr_9mmt-th

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM