github.com/kaptinlin/jsonschema@v0.4.6/const.go (about) 1 package jsonschema 2 3 import ( 4 "reflect" 5 ) 6 7 // EvaluateConst checks if the data matches exactly the value specified in the schema's 'const' keyword. 8 // According to the JSON Schema Draft 2020-12: 9 // - The value of the "const" keyword may be of any type, including null. 10 // - An instance validates successfully against this keyword if its value is equal to the value of the keyword. 11 // 12 // This function performs an equality check between the data and the constant value specified. 13 // If they do not match, it returns a EvaluationError detailing the expected and actual values. 14 // 15 // Reference: https://json-schema.org/draft/2020-12/json-schema-validation#name-const 16 func evaluateConst(schema *Schema, instance interface{}) *EvaluationError { 17 if schema.Const == nil || !schema.Const.IsSet { 18 return nil 19 } 20 21 // Special handling for null value comparison 22 if schema.Const.Value == nil { 23 if instance != nil { 24 return NewEvaluationError("const", "const_mismatch_null", "Value should be null") 25 } 26 return nil 27 } 28 29 // Handle numeric type comparisons 30 switch constVal := schema.Const.Value.(type) { 31 case float64: 32 switch instVal := instance.(type) { 33 case float64: 34 if constVal == instVal { 35 return nil 36 } 37 case int: 38 if constVal == float64(instVal) { 39 return nil 40 } 41 } 42 return NewEvaluationError("const", "const_mismatch", "Value does not match the constant value") 43 case int: 44 switch instVal := instance.(type) { 45 case float64: 46 if float64(constVal) == instVal { 47 return nil 48 } 49 case int: 50 if constVal == instVal { 51 return nil 52 } 53 } 54 return NewEvaluationError("const", "const_mismatch", "Value does not match the constant value") 55 } 56 57 // Use deep comparison for other types 58 if !reflect.DeepEqual(instance, schema.Const.Value) { 59 return NewEvaluationError("const", "const_mismatch", "Value does not match the constant value") 60 } 61 return nil 62 }