github.com/kaptinlin/jsonschema@v0.4.6/examples/basic/main.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "log" 6 7 "github.com/kaptinlin/jsonschema" 8 ) 9 10 func main() { 11 // Compile schema 12 compiler := jsonschema.NewCompiler() 13 schema, err := compiler.Compile([]byte(`{ 14 "type": "object", 15 "properties": { 16 "name": {"type": "string", "minLength": 2}, 17 "age": {"type": "integer", "minimum": 0} 18 }, 19 "required": ["name", "age"] 20 }`)) 21 if err != nil { 22 log.Fatal(err) 23 } 24 25 // Valid data 26 validData := map[string]interface{}{ 27 "name": "John", 28 "age": 30, 29 } 30 if schema.Validate(validData).IsValid() { 31 fmt.Println("✅ Valid data passed") 32 } 33 34 // Invalid data 35 invalidData := map[string]interface{}{ 36 "name": "J", // too short 37 "age": -1, // negative 38 } 39 result := schema.Validate(invalidData) 40 if !result.IsValid() { 41 fmt.Println("❌ Invalid data failed:") 42 for field, errors := range result.Errors { 43 fmt.Printf(" - %s: %v\n", field, errors) 44 } 45 } 46 }