1

我正在从这种类型的 jsons 过渡:

{
    "id": 1,
    "data": {
         "item_number": "4",
         ...
    }
}

{
    "id": 1,
    "data": {
        "itemNumbers": [4],
        ...
    }
}

我需要一个匹配这两个 json 的 jsonschema。

这是:

{
  "properties": {
    "id": {
      "enum": [
        1
      ]
    },
    "data": {
      "anyOf": [
        {
          "properties": {
            "item_number": {
              "enum": [
                "4"
              ]
            }
          }
        },
        {
          "properties": {
            "itemNumbers": {
              "contains": {
                "enum": [
                  4
                ]
              }
            }
          }
        }
      ]
    }
  },
  "required": [
    "id"
  ]
}

使用 python jsonschema 包,它匹配所有 jsons,无论项目编号如何。

任何帮助表示赞赏。

4

1 回答 1

1

您需要修改您的anyOfto oneOf(这不会改变您当前模式的任何内容,但会使意图更清晰)并添加additionalProperties: false到每个子模式中。

使用您的架构,"item_number": "4"anyOf[0] 的验证失败,但 anyOf[1] 的验证通过,因为没有约束item_number或未定义属性。

additionalProperties: false意味着任何未作为键包含在内的属性properties都将导致验证失败。

于 2019-01-03T09:14:05.387 回答