forked from kaptinlin/jsonschema
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprefixItems.go
57 lines (49 loc) · 2.46 KB
/
prefixItems.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package jsonschema
import (
"fmt"
"strconv"
"strings"
)
// EvaluatePrefixItems checks if each element in an array instance matches the schema specified at the same index in the 'prefixItems' array.
// According to the JSON Schema Draft 2020-12:
// - The value of "prefixItems" MUST be a non-empty array of valid JSON Schemas.
// - Validation succeeds if each element of the instance validates against the schema at the same position, if any.
// - This keyword does not constrain the length of the array; it validates only the prefix of the array up to the length of 'prefixItems'.
// - Produces an annotation value of the largest index validated if all items up to that index are valid. The value may be true if all items are valid.
// - Omitting this keyword implies an empty array behavior, meaning no validation is enforced on the array items.
//
// If validation fails, it returns a EvaluationError detailing the index and discrepancy.
func evaluatePrefixItems(schema *Schema, array []interface{}, evaluatedProps map[string]bool, evaluatedItems map[int]bool, dynamicScope *DynamicScope) ([]*EvaluationResult, *EvaluationError) {
if len(schema.PrefixItems) == 0 {
return nil, nil // If no prefixItems are defined, there is nothing to validate against.
}
invalid_indexs := []string{}
results := []*EvaluationResult{}
for i, itemSchema := range schema.PrefixItems {
if i >= len(array) {
break // Stop validation if there are more schemas than array items.
}
result, _, _ := itemSchema.evaluate(array[i], dynamicScope)
if result != nil {
results = append(results, result.SetEvaluationPath(fmt.Sprintf("/prefixItems/%d", i)).
SetSchemaLocation(schema.GetSchemaLocation(fmt.Sprintf("/prefixItems/%d", i))).
SetInstanceLocation(fmt.Sprintf("/%d", i)),
)
if result.IsValid() {
evaluatedItems[i] = true // Mark the item as evaluated if it passes schema validation.
} else {
invalid_indexs = append(invalid_indexs, strconv.Itoa(i))
}
}
}
if len(invalid_indexs) == 1 {
return results, NewEvaluationError("prefixItems", "prefix_item_mismatch", "Item at index {index} does not match the prefixItems schema", map[string]interface{}{
"index": invalid_indexs[0],
})
} else if len(invalid_indexs) > 1 {
return results, NewEvaluationError("prefixItems", "prefix_items_mismatch", "Items at index {indexs} do not match the prefixItems schemas", map[string]interface{}{
"indexs": strings.Join(invalid_indexs, ", "),
})
}
return results, nil
}