0

我以前写过一个 JSON 模式,但现在,当我试图让它更高级时,我卡住了。

(我对评论中的“良好实践”提示持开放态度)

(是$id可选的吗?为了简单起见,我应该在示例代码中删除它吗?)

目标:

我正在尝试example_obj使用递归使用的对象定义()创建模式。此对象可能只有 1 个参数(orandvalue)。但是在 json 的根目录中,我想添加 1 个附加属性。

json模式

{
  "definitions": {
    "example_obj": {
      "$id": "#/definitions/example_obj",
      "type": "object",
      "maxProperties": 1,
      "properties": {
        "or": {
          "$id": "#/definitions/example_obj/properties/or",
          "type": "array",
          "items": {
            "$id": "#/definitions/example_obj/properties/or/items",
            "$ref": "#/definitions/example_obj"
          }
        },
        "and": {
          "$id": "#/definitions/example_obj/properties/and",
          "type": "array",
          "items": {
            "$id": "#/definitions/example_obj/properties/and/items",
            "$ref": "#/definitions/example_obj"
          }
        },
        "value": {
          "$id": "#/definitions/example_obj/properties/value",
          "type": "string"
        }
      }
    }
  },
  "type": "object",
  "title": "The Root Schema",
  "required": ["filter_version"],
  "allOf": [
    {
      "$ref": "#/definitions/example_obj"
    },
    {
      "properties": {
        "filter_version": {
          "$id": "#/properties/filter_version",
          "type": "string",
          "pattern": "^([0-9]+\\.[0-9]+)$"
        }
      }
    }
  ]
}

我想通过验证的json:

{
  "filter_version": "1.0",
  "or": [
    {
      "and": [
        {
          "value": "subject"
        }
      ]
    },
    {
      "or": [
        {
          "value": "another subject"
        }
      ]
    }
  ]
}

问题:

当我尝试扩展example_obj根定义时,它似乎失败了,因为该example_obj对象在设计上不允许超过 1 个属性。

换句话说,似乎每次检查我添加的参数数量example_obj也是在附加属性(即filter_version)上执行的。

有谁知道在哪里放置“恰好 1 个参数”的检查,以便不对root对象进行评估?

尝试:

我尝试使用不同的方法来确定 的要求example_obj,但没有成功。就像替换"maxProperties": 1为:

"oneOf": [
  {
    "required": [
      "or"
    ]
  },
  {
    "required": [
      "and"
    ]
  },
  {
    "required": [
      "where"
    ]
  },
  {
    "required": [
      "where not"
    ]
  }
],

提前感谢您的帮助!!

使用在线模式验证器检查我的模式。

(最后我需要在 Python 中验证它,以防万一)

4

1 回答 1

0

您可以使用oneOf而不是maxProperties解决此问题。

{
  "type": "object",
  "properties": {
    "filter_version": {
      "type": "string",
      "pattern": "^([0-9]+\\.[0-9]+)$"
    }
  },
  "required": ["filter_version"],
  "allOf": [{ "$ref": "#/definitions/example_obj" }],
  "definitions": {
    "example_obj": {
      "type": "object",
      "properties": {
        "or": { "$ref": "#/definitions/example-obj-array" },
        "and": { "$ref": "#/definitions/example-obj-array" },
        "value": { "type": "string" }
      },
      "oneOf": [
        { "required": ["or"] },
        { "required": ["and"] },
        { "required": ["value"] }
      ]
    },
    "example-obj-array": {
      "type": "array",
      "items": { "$ref": "#/definitions/example_obj" }
    }
  }
}

PS你用$id错了。我知道有一个工具可以生成这样的模式并导致这种混乱。这里使用的方式$id是无操作。它没有伤害,但除了使您的架构膨胀之外,它不会做任何事情。

于 2019-10-23T17:12:39.483 回答