github.com/kaptinlin/jsonschema@v0.4.6/type.go (about)

     1  package jsonschema
     2  
     3  import (
     4  	"strings"
     5  )
     6  
     7  // EvaluateType checks if the data's type matches the type specified in the schema.
     8  // According to the JSON Schema Draft 2020-12:
     9  //   - The value of the "type" keyword must be either a string or an array of unique strings.
    10  //   - Valid string values are the six primitive types ("null", "boolean", "object", "array", "number", "string")
    11  //     and "integer", which matches any number with a zero fractional part.
    12  //   - If "type" is a single string, the data matches if its type corresponds to that string.
    13  //   - If "type" is an array, the data matches if its type corresponds to any string in that array.
    14  //
    15  // This method ensures that the data instance conforms to the type constraints defined in the schema.
    16  // If the instance does not conform, it returns a EvaluationResult detailing the expected and actual types.
    17  //
    18  // Reference: https://json-schema.org/draft/2020-12/json-schema-validation#name-type
    19  func evaluateType(schema *Schema, instance interface{}) *EvaluationError {
    20  	// Evaluate only if type constraints are specified in the schema
    21  	if len(schema.Type) == 0 {
    22  		return nil // No type constraints, so no validation needed
    23  	}
    24  
    25  	instanceType := getDataType(instance) // Determine the type of the provided instance
    26  
    27  	for _, schemaType := range schema.Type {
    28  		if schemaType == "number" && instanceType == "integer" {
    29  			// Special case: integers are valid numbers per JSON Schema specification
    30  			return nil
    31  		}
    32  		if instanceType == schemaType {
    33  			return nil // Correct type found, validation successful
    34  		}
    35  	}
    36  
    37  	// If no valid type match is found, generate a EvaluationResult
    38  	return NewEvaluationError("type", "type_mismatch", "Value is {received} but should be {expected}", map[string]interface{}{
    39  		"expected": strings.Join(schema.Type, ", "), // Expected types
    40  		"received": instanceType,                    // Actual type of the input data
    41  	})
    42  }