Specifying a square - dynamic minItems
/maxItems
for nested arrays?
#730
-
Hello! I hope this is the right place to ask this. I have searched in this board and in as many ways as I can think of across the internet, so hopefully this seemingly-simple question is not redundant. Is it possible to specify that one array's shape must be equal to anothers? Say I want to specify a 2D square array: the two arrays can be any length, but their lengths must be equal. I see in the spec that The purpose here is trying to generate JSON Schema representations of an n-dimensional array schema, where requirements like "array must be square" or "dimension 1 must be greater than dimension 2" are common. thanks in advance, sorry if this has been discussed elsewhere. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
So yes and no. Generally there's no way to specify a size of one array based on the size of another because there's no way to query the size of an array. If you know what sizes you want to support, this is proabably the brute-force-iest way with some consideration of not duplicating subschemas: {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "array",
"items": {
"type": "array",
"items": { /* item content */ }
},
"anyOf": [
{
"$ref": "#/$defs/size2",
"items": { "$ref": "#/$defs/size2" }
},
{
"$ref": "#/$defs/size3",
"items": { "$ref": "#/$defs/size3" }
},
{
"$ref": "#/$defs/size3",
"items": { "$ref": "#/$defs/size3" }
},
// ...
],
"$defs": {
"size2": {
"minItems": 2,
"maxItems": 2,
},
"size3": {
"minItems": 3,
"maxItems": 3,
},
"size4": {
"minItems": 4,
"maxItems": 4,
},
// ...
}
} I can't think of a good way to do this with dynamic references, though that was my first thought to try. |
Beta Was this translation helpful? Give feedback.
So yes and no.
Generally there's no way to specify a size of one array based on the size of another because there's no way to query the size of an array.
If you know what sizes you want to support, this is proabably the brute-force-iest way with some consideration of not duplicating subschemas: