github.com/kaptinlin/jsonschema@v0.4.6/dependentRequired.go (about) 1 package jsonschema 2 3 import ( 4 "github.com/goccy/go-json" 5 ) 6 7 // EvaluateDependentRequired checks that if a specified property is present, all its dependent properties are also present. 8 // According to the JSON Schema Draft 2020-12: 9 // - The "dependentRequired" keyword specifies properties that are required if a specific other property is present. 10 // - This keyword's value must be an object where each property is an array of strings, indicating properties required when the key property is present. 11 // - Validation succeeds if, whenever a key property is present in the instance, all properties in its array are also present. 12 // 13 // This method ensures that property dependencies are respected in the data instance. 14 // If a dependency is not met, it returns a EvaluationError detailing the issue. 15 // 16 // Reference: https://json-schema.org/draft/2020-12/json-schema-validation#name-dependentrequired 17 func evaluateDependentRequired(schema *Schema, object map[string]interface{}) *EvaluationError { 18 if schema.DependentRequired == nil { 19 return nil // No dependent required properties defined, nothing to do. 20 } 21 22 dependentMissingProps := make(map[string][]string) 23 24 for key, requiredProps := range schema.DependentRequired { 25 if _, keyExists := object[key]; keyExists { 26 var missingProps []string 27 for _, reqProp := range requiredProps { 28 if _, propExists := object[reqProp]; !propExists { 29 missingProps = append(missingProps, reqProp) 30 } 31 } 32 33 if len(missingProps) > 0 { 34 dependentMissingProps[key] = missingProps 35 } 36 } 37 } 38 39 if len(dependentMissingProps) > 0 { 40 missingPropsJSON, _ := json.Marshal(dependentMissingProps) 41 return NewEvaluationError("dependentRequired", "dependent_property_required", "Some required property dependencies are missing: {missing_properties}", map[string]interface{}{ 42 "missing_properties": string(missingPropsJSON), 43 }) 44 } 45 46 return nil 47 }