Home > Article > Backend Development > How to Validate JSON Format in Go?
In Go, you can encounter scenarios where you need to determine if a string is in JSON format. This article provides a solution to this requirement.
The json package in Go offers a straightforward approach to validate JSON strings. The following function uses this package to determine whether an input string is JSON:
func IsJSON(str string) bool { var js json.RawMessage return json.Unmarshal([]byte(str), &js) == nil }
The function uses the Unmarshal function to attempt to decode the input string into a RawMessage object. If the decoding is successful without errors, the function returns true, indicating that the string is valid JSON. Otherwise, it returns false.
To utilize the IsJSON function, you can implement it as follows:
func main() { testString := `{"name": "John", "age": 30}` if IsJSON(testString) { fmt.Println("It's JSON!") } else { fmt.Println("It's a normal string") } }
In this example, the IsJSON function is used to validate the testString variable. Since testString is in JSON format, the function will print "It's JSON!" to the console.
The above is the detailed content of How to Validate JSON Format in Go?. For more information, please follow other related articles on the PHP Chinese website!