Skip to content

Schema for dictionaries with dynamic keys #126

@oxidand

Description

@oxidand

I have yaml with a similar structure (but with more fields):

daemons:
  one:
    image: bash
    command:
      - echo 'one'
  two:
    image: busybox
    command:
      - echo 'two'

Keys one and two in this example are dynamic, but the structure of the object is always the same.

Without any annotations, it will generate a schema for each object separately:

      "properties": {
        "one": {
          "additionalProperties": false,
          "properties": {
            "command": {
              "items": {
                "anyOf": [
                  {
                    "required": [],
                    "type": "string"
                  }
                ],
                "required": []
              },
              "required": [],
              "title": "command",
              "type": "array"
            },
            // ...
        },
        "two": {
          // ...
        }
      },
      // ...

Ideally, I'd like to generate a schema like this:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "daemons": {
      "type": "object",
      "additionalProperties": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "image": { "type": "string" },
          "command": { "type": "array", "items": { "type": "string" } }
        },
        "required": ["command", "image"]
      },
      "required": []
    }
  },
  "required": ["daemons"]
}

Question №1: Is it possible to define a schema to handle "maps"? I know I can write an annotation to define all this, but I don't want to define the whole schema above the definition. It would be great if I could only add annotations for complex types. Or at least define types near each field, rather than in a long annotation above the dictionary.

I can bypass it with patternProperties:

# @schema
# required: false
# patternProperties:
#   ".*":
#     required: [image, command]
#     properties:
#       image:
#         type: string
#       command:
#         type: array
#         items:
#           type: string
# @schema
daemons:

And it works, except for one thing - required. I still get it in schema:

"daemons": {
  "additionalProperties": false,
  "patternProperties": {
    // ...
  },
  "required": [
    "one",
    "two"
  ],
  "title": "daemons"
},

Question №2: Is it a bug or am I doing something wrong?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions