How to check string is in json format

后端 未结 8 1481
广开言路
广开言路 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:59

    In searching for an answer to this question, I found https://github.com/asaskevich/govalidator, which was tied to this blog post which describes creating an input validator: https://husobee.github.io/golang/validation/2016/01/08/input-validation.html. Just in case someone is looking for a quick library on doing this, I thought it would be useful to put that tool in an easy-to-find place.

    This package uses the same method for isJSON that William King suggests, as follows:

    // IsJSON check if the string is valid JSON (note: uses json.Unmarshal).
    func IsJSON(str string) bool {
        var js json.RawMessage
        return json.Unmarshal([]byte(str), &js) == nil
    }
    

    This package gave me some greater insight into JSON in go, so it seemed useful to put here.

    0 讨论(0)
  • 2020-12-24 03:00

    This might be an older post to the actual function in the standard library.

    But you can just use the json.Valid() function in the "encoding/json" package.

       var tests = []string{
        `"Platypus"`,
        `Platypus`,
        `{"id":"1"}`,
        `{"id":"1}`,
    }
    
    for _, t := range tests {
        fmt.Printf("is valid: (%s) = %v\n", t, json.Valid([]byte(t)))
        
    }
    

    example https://play.golang.org/p/nfvOzQB919s

    0 讨论(0)
提交回复
热议问题