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
Select single argument from all arguments of variadic function
How to read/write from/to file in Golang?
Regular expression to extract numbers from a string in Golang
How to declare and access pointer variable?
Example: How to use ReadFull from IO Package in Golang?
How to import structs from another package in Go?
Most Helpful This Week
How to check if a string contains a white space in Golang?How to use a mutex to define critical sections of code and fix race conditions?Find element in a slice and move it to first position?Select single argument from all arguments of variadic functionReplace any non-alphanumeric character sequences with a dash using RegexRegular expression to validate email addressConvert Int data type to Int16 Int32 Int64Strip all white spaces, tabs, newlines from a stringHow to use for and foreach loop?Golang Get current Date and Time in EST, UTC and MST?