dq23171 2014-03-02 13:37
浏览 301
已采纳

如何检查字符串是否为json格式

I want to create a function to receive an input string which can be string in json format or just a string. For example, something easy like following function.

func checkJson(input string){
   if ... input is in json ... {
      fmt.Println("it's json!")
   } else {
      fmt.Println("it's normal string!")
   }
}
  • 写回答

7条回答 默认 最新

  • dongpan1416 2014-03-02 15:21
    关注

    I was unclear if you needed to know about just a "quoted string" or if you needed to know about json, or the difference between both of them, so this shows you how to detect both scenarios so you can be very specific.

    I posted the interactive code sample here as well: http://play.golang.org/p/VmT0BVBJZ7

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    func isJSONString(s string) bool {
        var js string
        return json.Unmarshal([]byte(s), &js) == nil
    
    }
    
    func isJSON(s string) bool {
        var js map[string]interface{}
        return json.Unmarshal([]byte(s), &js) == nil
    
    }
    
    func main() {
        var tests = []string{
            `"Platypus"`,
            `Platypus`,
            `{"id":"1"}`,
        }
    
        for _, t := range tests {
            fmt.Printf("isJSONString(%s) = %v
    ", t, isJSONString(t))
            fmt.Printf("isJSON(%s) = %v
    
    ", t, isJSON(t))
        }
    
    }
    

    Which will output this:

    isJSONString("Platypus") = true
    isJSON("Platypus") = false
    
    isJSONString(Platypus) = false
    isJSON(Platypus) = false
    
    isJSONString({"id":"1"}) = false
    isJSON({"id":"1"}) = true
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数