iooi
iooi

Reputation: 523

How to add required to sub array in a json schema?

I'm creating a json schema to define necessary data with data types. There is some data need to be set into required filed. But didn't find how to do it in its document.

For this json schema:

{
  "type": "object",
  "required": [
    "version",
    "categories"
  ],
  "properties": {
    "version": {
      "type": "string",
      "minLength": 1,
      "maxLength": 1
    },
    "categories": {
      "type": "array",
      "items": [
        {
          "title": {
            "type": "string",
            "minLength": 1
          },
          "body": {
            "type": "string",
            "minLength": 1
          }
        }
      ]
    }
  }
}

json like

{
   "version":"1",
   "categories":[
      {
         "title":"First",
         "body":"Good"
      },
      {
         "title":"Second",
         "body":"Bad"
      }
   ]
}

I want to set title to be required, too. It's in a sub array. How to set it in json schema?

Upvotes: 0

Views: 404

Answers (1)

Relequestual
Relequestual

Reputation: 12335

There are a few things wrong with your schema. I'm going to assume you're using JSON Schema draft 2019-09.

First, you want items to be an object, not an array, as you want it to apply to every item in the array.

If "items" is a schema, validation succeeds if all elements in the
array successfully validate against that schema.

If "items" is an array of schemas, validation succeeds if each
element of the instance validates against the schema at the same
position, if any.

https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-02#section-9.3.1.1

Second, if the value of items should be a schema, you need to treat it like a schema in its own right.

If we take the item from your items array as a schema, it doesn't actually do anything, and you need to nest it in a properties keyword...

{
  "properties": {
    "title": {
      "type": "string",
      "minLength": 1
    },
    "body": {
      "type": "string",
      "minLength": 1
    }
  }
}

Finally, now your items keyword value is a schema (subschema), you can add any keywords you can normally use, such as required, the same as you have done previously.

{
  "required": [
    "title"
  ],
  "properties": {
    ...
  }
}

Upvotes: 1

Related Questions