Home > Software engineering >  How to define nested arrays in JSON schema where the base type of array items is specific type
How to define nested arrays in JSON schema where the base type of array items is specific type

Time:10-27

I am using python's jsonschema to validate YAML files. One of the things I can't figure out how to do is allow nested arrays but enforce the base type of all array items are strings. I need this capability to handle YAML anchors. For example, how would I construct the schema to ensure that a, b, c,... are all strings? For reference, I don't know how nested this array will be so I don't think using simple anyOf would work.

["a", ["b", ["c"]], ...]

I referenced the docs about recursion and this seems like what I need, I just don't understand it well enough to implement it for this case.

Ideally, I would like all base items of the array to be unique, but this might be asking too much as I can easily accomplish checking that in python after flattening the array.

CodePudding user response:

For a single level array of strings:

{
  "type": "array",
  "items": {
    "type": "string"
  },
  "uniqueItems": true
}

You can make the items schema recursive by allowing it to be an array of arrays, or strings:

{
  "$defs": {
    "nested_array": {
      "type": "array",
      "items": {
        "anyOf": [
          { "type": "string" },
          { "$ref": "#/$defs/nested_array" }
        ]
      },
      "uniqueItems": true
    }
  },
  "$ref": "#/$defs/nested_array"
}

reference: https://json-schema.org/understanding-json-schema/reference/array.html

  • Related