Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
621 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 Reply

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"] }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...