Home  >  Article  >  Backend Development  >  How to Validate JSON Format in Go?

How to Validate JSON Format in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-09 18:28:02273browse

How to Validate JSON Format in Go?

Validating 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.

Using the json package

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.

Example usage

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn