简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM