【问题标题】:Go: What's the best way to detect invalid JSON string characters?Go:检测无效 JSON 字符串字符的最佳方法是什么?
【发布时间】:2018-02-21 02:18:26
【问题描述】:

检测 Go 字符串是否包含 JSON 字符串中的无效字符的最佳、最有效的方法是什么?换句话说,Go 相当于这个Java question 的答案?难道只是为了使用 strings.ContainsAny(假设为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")
}

【问题讨论】:

  • 高效在什么意义上?快速地?最低功耗? CPU 指令数量最少?在 Nacl 上运行?最短持续时间/瓦特?最少的缓存未命中数?容易明白?在调试期间最有效? JSON 规范更改最容易更改?
  • @Volker 是的。了解/查看/记录所有选项和权衡会很有用。
  • “所有选项和权衡”非常广泛。如果您有一个特定的优化目标,该目标可能足够窄,可以回答 SO。

标签: json string go unicode control-characters


【解决方案1】:

如果您正在寻找识别控制字符(如您指出的 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

【讨论】:

    猜你喜欢
    • 2017-02-03
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    相关资源
    最近更新 更多