Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

jsonschema - JSON schema validate head and tail of and array

Hi I have a simple JSON array where the first item is always a string and 2..N items could be boolean or integer. eg.

[ "string", 1, 1, true, 1] // valid
[ "string", 1,1,"string" ]  // invalid
[ "string", 1,1,1,1,1,1] // valid

I have tried to come up with a json schema to validate this but unfortunately says all the above are valid. Not sure if its possible to validate this in json shema ie a head and a tail? This list (array) can have any number of items. my attempt:

{
    "type" : "array",
    "items" : [
        { "$ref": "#/definitions/head" },
        { "$ref": "#/definitions/tail" }
    ],
     
     "definitions": {
     "head" :  {
          "type": "string"
         },
    "tail": { "anyOf" : [ 
            { "type" : "number" },
            { "type" : "boolean" }
        ]}
     }
}
question from:https://stackoverflow.com/questions/65931437/json-schema-validate-head-and-tail-of-and-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do this with the array-form of items combined with additionalItems. items describes the head and additionalProperties describes the tail.

{
  "type": "array",
  "items": [{ "type": "string" }],
  "additionalItems": { "type": ["number", "boolean"] }
}

In the new draft 2020-12, the keywords have changed, but you can do the same thing.

{
  "type": "array",
  "prefixItems": [{ "type": "string" }],
  "items": { "type": ["number", "boolean"] }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...