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
How to concatenate two or more slices in Golang?
Convert Int data type to Int16 Int32 Int64
How to Remove duplicate values from Slice?
Get Year, Month, Day, Hour, Min and Second from a specified date
Pass different types of arguments in variadic function
Sierpinski Carpet in Go Programming Language
Split a character string based on change of character
Passing multiple string arguments to a variadic function
How to blur an image in Golang?
How to check if a string contains only letters in Golang?
Most Helpful This Week
How to import structs from another package in Go?How to check string contains uppercase lowercase character in Golang?Converting Int data type to Float in GoSierpinski triangle in Go Programming LanguageVarious examples of Carbon date-time package in GolangHow to Convert string to integer type in Go?How to compare equality of struct, slice and map?How to check if a map contains a key in Go?Dynamic JSON parser without Struct in GolangHow to check UPPERCASE characters in a string in Golang?