Open jawn-smith opened 2 years ago
Here is what I am trying to do:
package main import ( "fmt" "strings" "github.com/xeipuuv/gojsonschema" "gopkg.in/yaml.v2" ) func main() { yamlFile1 := ` test-string1: "foo" test-string2: "bar" ` yamlFile2 := ` test-string1: "baz" ` schemaFile := ` { "$schema": "http://json-schema.org/draft/2020-12/schema", "$ref": "#/$defs/TestStruct", "$defs": { "TestStruct": { "properties": { "TestString1": { "type": "string" }, "TestString2": { "type": "string" } }, "additionalProperties": false, "type": "object", "required": [ "TestString1", "TestString2" ] } } }` type TestStruct struct { TestString1 string `yaml:"test-string1" json:"TestString1"` TestString2 string `yaml:"test-string2" json:"TestString2"` } var testStruct1 TestStruct yamlReader1 := strings.NewReader(yamlFile1) yaml.NewDecoder(yamlReader1).Decode(&testStruct1) var testStruct2 TestStruct yamlReader2 := strings.NewReader(yamlFile2) yaml.NewDecoder(yamlReader2).Decode(&testStruct2) sl := gojsonschema.NewSchemaLoader() loader1 := gojsonschema.NewStringLoader(schemaFile) sl.AddSchemas(loader1) testStructLoader1 := gojsonschema.NewGoLoader(testStruct1) testStructLoader2 := gojsonschema.NewGoLoader(testStruct2) schema, _ := sl.Compile(loader1) result, _ := schema.Validate(testStructLoader1) if result.Valid() { fmt.Println("testStruct1 successfully validated") } else { fmt.Println("testStruct1 FAILED validation") } result, _ = schema.Validate(testStructLoader2) if result.Valid() { fmt.Println("testStruct2 successfully validated") } else { fmt.Println("testStruct2 FAILED validation") } }
In this example, the JSON schema requires both "TestString1" and "TestString2" to be present. It isn't present in one of the example YAML files, but it successfully validates anyway. Running this code yields:
testStruct1 successfully validated testStruct2 successfully validated
Looking at the gojsonschema code, it only checks for if they key is present in the struct, rather than if the key has a non ZeroType value.
Here is what I am trying to do:
In this example, the JSON schema requires both "TestString1" and "TestString2" to be present. It isn't present in one of the example YAML files, but it successfully validates anyway. Running this code yields:
Looking at the gojsonschema code, it only checks for if they key is present in the struct, rather than if the key has a non ZeroType value.