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
Split a character string based on change of character
How to check if a string contains a white space in Golang?
How to verify a string only contains letters, numbers, underscores, and dashes in Golang?
How to update content of a text file?
Find length of Channel, Pointer, Slice, String and Map
How To Make HTTP Requests in Go?
Most Helpful This Week
Example: How to use ReadFull from IO Package in Golang?Select single argument from all arguments of variadic functionConvert specific UTC date time to PST, HST, MST and SGTHigher Order Functions in GolangURL parser in GolangDifferent ways to convert Byte Array into StringReplace first occurrence of string using RegexpHow to find the type of the variable by different ways in Golang?Regular expression to validate common Credit Card NumbersVarious examples of printing and formatting in Golang