【问题标题】:Is there any mechanism in jsonschema to define custom validators for arrays?jsonschema 中是否有任何机制可以为数组定义自定义验证器?
【发布时间】:2020-06-30 01:03:57
【问题描述】:

我希望能够编写一个 jsonschema 片段,例如:

{
   "type":"array",
   "items":{
      "type":"number",
      "lag":2
   }
}

在一个数值全为 2 的数字数组上成功:例如

[ 1, 3, 5, 7 ]

我能够将自定义格式描述为从列表到布尔的函数。

这可能吗?

【问题讨论】:

    标签: jsonschema python-jsonschema


    【解决方案1】:

    不,没有。您可以在此处找到可用的数组验证: https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.6.4

    您可以指定一个数字必须是 x 的倍数: https://json-schema.org/understanding-json-schema/reference/numeric.html#multiples 但当然这只是你想要实现的一部分。

    【讨论】:

    • 将集合限制为 x 的倍数不会执行 OP 想要执行的“部分操作”,除非 x = 1。
    【解决方案2】:

    如果你的字面意思是奇数,你可以这样做:

    {
       "type":"array",
       "items":{
          "allOf": [{"type":"number"}, {"not": {"multipleOf": 2}}],
       }
    }
    

    【讨论】:

      【解决方案3】:

      这很简单。我定义了一个自定义验证器https://python-jsonschema.readthedocs.io/en/stable/creating/。 不幸的是,我必须在验证器中验证该实例是一个数字数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-05
        • 1970-01-01
        • 2016-01-24
        • 1970-01-01
        • 1970-01-01
        • 2012-05-05
        • 2022-11-08
        • 1970-01-01
        相关资源
        最近更新 更多