douzhiji2020
2017-09-12 14:45
浏览 212

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

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

图片转代码服务由CSDN问答提供 功能建议

检测Go字符串是否包含JSON字符串中无效字符的最佳,最有效方法是什么? 换句话说,此 Java问题的答案等同于Go? 只是使用 strings.ContainsAny (假设 ASCII控制字符)?

  ctlChars:=字符串(  [] 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 string.ContainsAny(str,ctlChars){
 println(“ has control chars”)\  n} 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongzhenshen7435 2017-09-12 16:01
    已采纳

    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

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题