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:
<nil>
cannot parse JSON: cannot parse object: cannot parse object value: cannot parse number: expecting 0..9 digit, got '; unparsed tail: "'John', age: 23,}"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.
goos: linux
goarch: amd64
pkg: github.com/ayoisaiah/random
cpu: Intel(R) Core(TM) i7-7560U CPU @ 2.40GHz
BenchmarkStdJSON/small.json-4         	  939679	      1209 ns/op
BenchmarkStdJSON/medium.json-4        	   84142	     15159 ns/op
BenchmarkStdJSON/large.json-4         	    6980	    227489 ns/op
BenchmarkFastJSON/small.json-4        	 2354534	       477.0 ns/op
BenchmarkFastJSON/medium.json-4       	  246301	      6156 ns/op
BenchmarkFastJSON/large.json-4        	   14686	     84331 ns/op
PASS
ok  	github.com/ayoisaiah/random	10.461sThanks for reading, and happy coding!