代码之家  ›  专栏  ›  技术社区  ›  Ron

JSonSchema属性根据父对象有条件地必需

  •  2
  • Ron  · 技术社区  · 8 年前

    根据这个问题 jsonschema attribute conditionally required ,我可以应用条件必需属性。但是,它只能依赖于同一级别对象上的属性。在某些情况下,我希望一个所需的属性依赖于其父对象属性,是否可能?对于以下示例:

    {
      type: 'object',
      properties: {
        { 
          os: { type: 'string', enum: ['macOs', 'windows'] },
          specs: {
            macModel: { 
              type: 'string', 
              enum: ['macbook air', 'macbook pro', 'macbook']
            },
            memory: { type: 'number' }
          }
        }
      }
    }
    

    是否可以满足此要求: /规格/型号 仅当 操作系统 等于 马科斯 ?

    1 回复  |  直到 7 年前
        1
  •  3
  •   Jason Desrosiers    8 年前

    {
      "type": "object",
      "properties": {
        "os": { "enum": ["macOs", "windows"] },
        "specs": {
          "macModel": { "enum": ["macbook air", "macbook pro", "macbook"] },
          "memory": { "type": "number" }
        }
      },
      "allOf": [{ "$ref": "#/definitions/os-macOs-requires-macModel" }],
      "definitions": {
        "os-macOs-requires-macModel": {
          "anyOf": [
            { "not": { "$ref": "#/definitions/os-macOs" } },
            { "$ref": "#/definitions/requires-macModel" }
          ]
        },
        "os-macOs": {
          "properties": {
            "os": { "const": "macOs" }
          },
          "required": ["os"]
        },
        "requires-macModel": {
          "properties": {
            "specs": {
              "required": ["macModel"]
            }
          }
        }
      }
    }
    

    /definitions/requires-macModel required

    if then