douzhiji2020 2017-09-12 14:45
浏览 221
已采纳

前往:检测无效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")
}
  • 写回答

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度