How to Verify the Validity of a JSON String in Go
If you’re looking for a way to verify if a string is valid JSON in Go regardless of its schema, the encoding/json
package has you covered, but there’s a third-party JSON library worth checking out.
The easiest way to verify if a string is valid JSON in Go is to use the Valid()
method provided by the standard library encoding/json
package:
func main() {
validJSON := `{"name": "John", "age": 23}`
invalidJSON := `{"name": 'John', age: 23,}`
fmt.Println(json.Valid([]byte(validJSON))) // true
fmt.Println(json.Valid([]byte(invalidJSON))) // false
}
While this method solves this problem sufficiently, a faster solution exists in
the fastjson package. It provides a
Validate()
or ValidateBytes()
method that can be several times faster than
json.Valid()
.
Once you’ve imported the library to your project, you can use the
fastjson.Validate()
method as shown below:
func main() {
validJSON := `{"name": "John", "age": 23}`
invalidJSON := `{"name": 'John', age: 23,}`
fmt.Println(fastjson.Validate(validJSON))
fmt.Println(fastjson.Validate(invalidJSON))
}
And here’s the output you can expect from running the program above:
The major difference here is that fastjson.Validate()
uses an error to
indicate that the string is not valid JSON unlike json.Valid()
which uses a
boolean. The error will be nil
if the string is valid JSON.
Here are some benchmark results that show how much faster fastjson.Validate()
is using a variety of sources.
Thanks for reading, and happy coding!