需要数组中的特定项

时间:2017-06-23 06:43:53

标签: json jsonschema

我有以下json对象:

{
  "my_items": [
    { "a": "primary", n: 1 },
    { "b": "secondary", n: 2 },
    { "b": "secondary", n: 3 }
  ]
}

my_items列表中的所有项目都应该是唯一的。现在,我需要使用以下规则验证整个json对象:

  

它可能包含零个或多个"type": "secondary"项,但绝对必须包含一个且只有"type": "primary"的项目。

如何使用最新的json-schema来表达?

我想出following

var schema = {
  "definitions": {
    "primary_item": {
      "type": "object",
      "properties": {
        "a": {
          "type":"string",
          "enum":["primary"]
        }
      }
    },
    "secondary_item": {
      "type": "object",
      "properties": {
        "b": {
          "type": "string",
          "enum":["secondary"]
        }
      }
    }
  },
  "type": "object",
  "properties": {
    "my_items": {
      "type": "array",
      "minItems": 1,
      "contains": {"$ref": "#/definitions/primary_item"},
      "items": {
        "anyOf": [
          {"$ref": "#/definitions/primary_item"},
          {"$ref": "#/definitions/secondary_item"}
        ],
        "additionalProperties": false
      }
    }
  },
  "additionalProperties": false
};

var validate = ajv.compile(schema);

test({
  "my_items": [
    {"a": "primary"},
    {"b": "secondary"},
    {"b": "secondary"}
  ]
});

但测试失败,出现以下错误:

Invalid: data.my_items[0] should NOT have additional properties, data.my_items[1] should NOT have additional properties, data.my_items[2] should NOT have additional properties

1 个答案:

答案 0 :(得分:0)

JSON Schema中没有办法断言数组只包含一个东西。你可以声称至少有一个,但这是你能做的最好的。最接近的是要求primary_item是数组中的第一个元素。

{
  "type": "object",
  "properties": {
    "my_items": {
      "type": "array",
      "items": [
        {"$ref": "#/definitions/primary_item"}
      ],
      "additionalItems": {"$ref": "#/definitions/secondary_item"}
    }
  },
  "additionalProperties": false,
  "definitions": {
    "primary_item": {
      "type": "object",
      "properties": {
        "a": { "enum":["primary"] }
      },
      "additionalProperties": false
    },
    "secondary_item": {
      "type": "object",
      "properties": {
        "b": { "enum":["secondary"] }
      },
      "additionalProperties": false
    }
  }
}

修改

回应评论

  

我想知道是否可以使用两个概念表达一个且只有一个at least one + unique

是。如果您的数组项是唯一的,则可以执行以下操作。

{
  "type": "object",
  "properties": {
    "my_items": {
      "type": "array",
      "items": { "$ref": "#/definitions/my_item" },
      "allOf": [{"$ref": "#/definitions/contains_primary_item"}],
      "uniqueItems": true
    }
  },
  "additionalProperties": false,
  "definitions": {
    "my_item": {
      "type": "object",
      "properties": {
        "a": { "type": "string" }
      },
      "additionalProperties": false
    },
    "primary_item": {
      "type": "object",
      "properties": {
        "a": { "enum":["primary"] }
      },
      "additionalProperties": false
    },
    "contains_primary_item": {
      "not": {
        "items": {
          "not": { "$ref": "#/definitions/primary_item" }
        }
      }
    }
  }
}