模式验证,如何根据较低级别的条件强制执行顶级属性

问题描述 投票:1回答:1

我正在尝试编写一个模式来在将其解析为JSON之后验证yaml文件。

假设这是我的.yml文件,包含2个顶级属性,汽车和车库。

汽车是可选的,而车库是必需的。

然而,车库的一个子属性是汽车。如果定义了车库下的车辆,我希望架构确保顶级车辆也被定义。否则,架构将无效

cars:
  - BMW
  - Mercedes-Benz
  - Audi

garage:
  location: Miami
  cars:
    - BMW
    - Audi

我的架构:

{
  properties: {
    cars: {
       type: 'array',
       items: {
          type: 'string'
       }
     },
    garage: {
      type: 'object',
      properties: {
          location: {
            type: 'string'
           },
          cars: {
            type: 'array'
         }
    },
 required: ['garage']
}}

所以我尝试在顶层做一个if-else

{
  if: { properties: { garage: { cars: {type: 'array'}}}},
  then: {required:['cars']},
  properties: {
    cars: {
       type: 'array',
       items: {
          type: 'string'
       }
     },
    garage: {
      type: 'object',
      properties: {
          location: {
            type: 'string'
           },
          cars: {
            type: 'array'
         }
    },
 required: ['garage']
}}

但似乎我做错了或者没有达到那个目的。

在顶层执行任何操作以匹配子模式对我来说都不起作用..

有帮助吗?

json schema jsonschema json-schema-validator ajv
1个回答
0
投票

if的值必须是JSON Schema。如果您自己将if的值作为JSON模式并测试将其应用于JSON实例中的正确位置的验证结果,则可以帮助您调试此类问题。

在你的if块中,你需要将cars放在properties下,就像你在主模式中所做的一样。

您可能还想在if区块中制作车库和汽车。]

但是,您无法定义要将garage.cars中的值包含在cars数组中。

© www.soinside.com 2019 - 2024. All rights reserved.