Different ways to validate JSON string
Check if string is valid JSON
In the below program isJSON function is used to validate given string contains valid JSON or not.
Example
package main
import (
"encoding/json"
"fmt"
)
var Object = `{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}`
var Array = `[{"key": "value1"}, {"key": "value2"}]`
func isJSON(s string) bool {
var js interface{}
return json.Unmarshal([]byte(s), &js) == nil
}
func main() {
val1 := isJSON(Object)
fmt.Println(val1)
val2 := isJSON(Array)
fmt.Println(val2)
}
Output
true
true
JSON validate using Standard Library function
Example
package main
import (
"fmt"
"encoding/json"
)
func main() {
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)))
}
}
Output
Is valid: ("Platypus") = true
Is valid: (Platypus) = false
Is valid: ({"id":"1"}) = true
Is valid: ({"id":"1}) = false
Most Helpful This Week
Regular expression to extract filename from given path in Golang
How to blur an image in Golang?
How to extract text from between html tag using Regular Expressions in Golang?
How to fetch an Integer variable as String in Go?
Simple function with parameters in Golang
Regular Expression to get a string between parentheses in Golang
Creating a Function in Golang
Copy an array by value and reference into another array
How to write backslash in Golang string?
Regular expression to validate the date format in "dd/mm/yyyy"
Most Helpful This Week
How to read names of all files and folders in current directory?How can we reverse a simple string in Go?Closures Functions in GolangReplace numbers by zero from stringExample to handle GET and POST request in GolangRegular expression to extract all Non-Alphanumeric Characters from a StringHow to convert Go struct to JSON?How to Remove duplicate values from Slice?How to create Empty and Nil Slice?Get current date and time in various format in golang