【问题标题】:How to write a schema to constrain some of the properties with one/any of the sub-schemas?如何编写一个模式来用一个/任何一个子模式来约束一些属性?
【发布时间】:2023-02-09 06:02:42
【问题描述】:

我可以验证两者吗

name: "range_1"
step: 1
start: 0
stop: 10

name: "range_2"
step: 1
center: 5
span: 5

用类似的东西

properties:
    name:
        type: "string"
    stop:
        type: number
    oneOf:
    -   start:
            type: number
        step:
            type: number
    -   center:
            type: number
        span:
            type: number

现在我在 Python 中使用jsonschema,但它抱怨jsonschema.exceptions.SchemaError: <the array in oneOf> is not of type 'object', 'boolean'

仅针对 namestep 进行验证或针对所有可能的密钥进行验证显然可行,但它们对我来说似乎都不是最佳选择。

【问题讨论】:

    标签: yaml jsonschema


    【解决方案1】:

    您需要将 oneOf 关键字移出 properties 对象,因为 properties 对象中的所有内容都被解释为数据中的预期值。

    此外,添加 required 属性以使值成为强制值是有意义的。最后,如果你想确保没有其他值被排除在外,你可以使用additionalProperties: false。但请注意,您必须再次重复 oneOf 模式中的“父”属性。如需进一步阅读,我推荐this example

    放在一起,您可以使用以下架构(请参阅live example here):

    ---
    properties:
      name:
        type: string
      step:
        type: number
    oneOf:
    - properties:
        name: true
        step: true
        start:
          type: number
        stop:
          type: number
      required:
      - start
      - stop
      additionalProperties: false
    - properties:
        name: true
        step: true
        center:
          type: number
        span:
          type: number
      required:
      - center
      - span
      additionalProperties: false
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-06
      • 2011-12-06
      • 1970-01-01
      • 2015-08-02
      • 1970-01-01
      • 2011-05-09
      • 2016-10-17
      • 2020-04-12
      相关资源
      最近更新 更多