【问题标题】:How to define nested arrays in JSON schema where the base type of array items is specific type如何在 JSON 模式中定义嵌套数组,其中数组项的基本类型是特定类型
【发布时间】:2021-10-26 17:01:31
【问题描述】:

我正在使用python's jsonschema 来验证 YAML 文件。我不知道该怎么做的一件事是允许嵌套数组,但强制所有数组项的基本类型是字符串。我需要这种能力来处理 YAML 锚。例如,我将如何构造模式以确保 abc、... 都是字符串?作为参考,我不知道这个数组是如何嵌套的,所以我认为使用简单的anyOf 是行不通的。

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

我参考了有关 recursion 的文档,这似乎是我需要的,我只是不太了解它,无法在这种情况下实现它。

理想情况下,我希望数组的所有基本项都是唯一的,但这可能要求太多,因为我可以在展平数组后轻松地在 python 中完成检查。

【问题讨论】:

    标签: python json jsonschema json-schema-validator


    【解决方案1】:

    对于单级字符串数组:

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

    您可以通过将 items 模式设为数组或字符串的数组来递归:

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

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

    【讨论】:

    • 太棒了,这似乎可以解决问题。它不能确保实际的基本项目是唯一的字符串,但它足够好,我可以在 python 中展平数组后检查它。谢谢!
    猜你喜欢
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 2022-01-03
    • 2021-05-31
    相关资源
    最近更新 更多