Skip to content

Instantly share code, notes, and snippets.

@brandtkeller
Created December 3, 2024 22:16
Show Gist options
  • Save brandtkeller/4b998b2630235b8c3787da9a4a44fb0f to your computer and use it in GitHub Desktop.
Save brandtkeller/4b998b2630235b8c3787da9a4a44fb0f to your computer and use it in GitHub Desktop.
json schema validation
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/qri-io/jsonschema"
)
// ValidateJSONSchema validates if a given JSON schema file is valid.
func ValidateJSONSchema(filePath string) error {
// Read the schema file
schemaData, err := ioutil.ReadFile(filePath)
if err != nil {
return fmt.Errorf("failed to read schema file: %w", err)
}
// Parse the schema into a jsonschema.Schema
var rawSchema map[string]interface{}
if err := json.Unmarshal(schemaData, &rawSchema); err != nil {
return fmt.Errorf("failed to parse schema: %w", err)
}
schemaLoader := &jsonschema.Schema{}
if err := schemaLoader.UnmarshalJSON(schemaData); err != nil {
return fmt.Errorf("invalid JSON schema: %w", err)
}
return nil
}
func main() {
// Path to a valid schema file
validSchemaPath := "../lula-nacx/src/pkg/common/schemas/validation.json"
if err := ValidateJSONSchema(validSchemaPath); err != nil {
fmt.Println("Schema is invalid:", err)
} else {
fmt.Println("Schema is valid")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment