How to check string is in json format

后端 未结 8 1480
广开言路
广开言路 2020-12-24 02:17

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.



        
相关标签:
8条回答
  • 2020-12-24 02:35

    For example,

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    func isJSONString(s string) bool {
        var js string
        err := json.Unmarshal([]byte(s), &js)
        return err == nil
    }
    
    func main() {
        fmt.Println(isJSONString(`"Platypus"`))
        fmt.Println(isJSONString(`Platypus`))
    }
    

    Output:

    true
    false
    
    0 讨论(0)
  • 2020-12-24 02:36

    how about you use something like this:

    if err := json.Unmarshal(input, temp_object); err != nil {
        fmt.Println("it's normal string!")
    } else {
        fmt.Println("it's json!")
    }
    
    0 讨论(0)
  • 2020-12-24 02:43

    Standard encoding/json library contains json.Valid function starting from go 1.9 - see https://github.com/golang/go/issues/18086 . This function may be used for checking whether the provided string is a valid json:

    if json.Valid(input) {
        // input contains valid json
    }
    

    But json.Valid may be quite slow comparing to third-party solutions such as fastjson.Validate, which is up to 5x faster than the standard json.Valid - see json validation section in benchmarks.

    0 讨论(0)
  • 2020-12-24 02:43

    The current accepted answer (as of July 2017) fails for JSON arrays and hasn't been updated: https://repl.it/J8H0/10

    Try this:

    func isJSON(s string) bool {
      var js interface{}
      return json.Unmarshal([]byte(s), &js) == nil
    }
    

    Or William King's solution, which is better.

    0 讨论(0)
  • 2020-12-24 02:47

    For anyone else looking for a way to validate any JSON string regardless of schema, try the following:

    func IsJSON(str string) bool {
        var js json.RawMessage
        return json.Unmarshal([]byte(str), &js) == nil
    }
    
    0 讨论(0)
  • 2020-12-24 02:50

    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\n", t, isJSONString(t))
            fmt.Printf("isJSON(%s) = %v\n\n", 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
    
    0 讨论(0)
提交回复
热议问题