Как проверить вложенный словарь объекта в Цербере - PullRequest
1 голос
/ 17 января 2020

Вот пример данных, которые необходимо проверить. Ключи во вложенном словаре employee_eligibility - это числовая строка «[0-9] +».

{
  "client_id": 1,
  "subdomain": "Acme",
  "shifts": [
    20047, 20048, 20049
  ],
  "employee_eligibility": {
    "1": {
      "20047": 1,
      "20048": 0,
      "20049": 1
    },
    "2": {
      "20047": 1,
      "20048": 0,
      "20049": 1
    },
    "3": {
      "20047": 1,
      "20048": 1,
      "20049": 0
    }
  }
}

Я написал следующую схему для проверки:

    {
        "client_id": {"type": "integer"},
        "subdomain": {"type": "string"},
        "shifts": {"type": "list", "schema": {"type": "integer"}},
        "employee_eligibility": {
            "type": "dict",
            "keysrules": {"type": "string", "regex": "[0-9]+"},
            "schema": {
                "type": "dict",
                "keysrules": {"type": "string", "regex": "[0-9]+"},
                "schema": {"type": "integer"}
            }
        },
    }

Когда я запускаю проверку, я получаю следующую ошибку:

{'employee_eligibility': ['must be of dict type']}

1 Ответ

2 голосов
/ 17 января 2020

Ваша схема немного отключена, вам нужно использовать valuesrules для проверки значений ваших словарей.

schema = {
    "client_id": {"type": "integer"},
    "subdomain": {"type": "string"},
    "shifts": {"type": "list", "schema": {"type": "integer"}},

    # `employee_eligibility` is a dictionary
    "employee_eligibility": {
        "type": "dict",

        # the keys in `employee_eligibility` are strings matching this regex
        "keysrules": {"type": "string", "regex": "^[0-9]+"},

        # the values in `employee_eligibility` are also dictionaries with keys
        # that are strings that match this regex and integer values
        "valuesrules": {
            "type": "dict",
            "keysrules": {"type": "string", "regex": "^[0-9]+"},
            "valuesrules": {"type": "integer"},
        },
    },
}

edit: добавлены некоторые комментарии, чтобы комментировать пример

...