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.
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.
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