JSONSchema和验证子对象属性

7

给定以下JSON对象:

{
    "objects": {
        "foo": {
            "id": 1,
            "name": "Foo"
        },
        "bar": {
            "id": 2,
            "name": "Bar"
        }
    }
}
这是一个包含子对象的对象,每个子对象都具有相同的结构 - 它们都是相同的类型。每个子对象都有唯一的键,因此它的行为类似于命名数组。 我想验证objects属性中的每个对象是否符合JSON Schema参考规范。 如果objects属性是一个数组,例如:
{
  "objects": [
    {
      "id": 1,
      "name": "Foo"
    },
    {
      "id": 2,
      "name": "Bar"
    }  
  ]
}   

我可以使用模式定义来验证这个,比如:

{
  "id": "my-schema",
  "required": [
    "objects"
  ],
  "properties": {
    "objects": {
      "type": "array",
      "items": {
        "type": "object",
        "required": [
          "id",
          "name"
        ],
        "properties": {
          "id": {
            "type": "integer"
          },
          "name": {
            "type": "string"
          }
        }
      }
    }
  }
}
这是通过将 type 设置为 array 实现的,从而允许验证 items。 那么,是否可以使用嵌套对象实现类似的功能呢? 谢谢!
2个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
4
您可以尝试以下方法:

您可以尝试以下方法:

{
  "id": "my-schema",
  "type": "object",
  "properties": {
    "objects": {
      "type": "object",
      "patternProperties": {
        "[a-z]+": {
          "type": "object",
          "properties": {
            "id": {
              "type": "integer"
            },
            "name": {
              "type": "string"
            }
          },
          "additionalProperties": false,
          "required": [
            "id",
            "name"
          ]
        }
      }
    }
  }
}

3
以上回答适用于将对象属性名称限制为小写字母。如果您不需要限制属性名称,则更简单:
{
  "id": "my-schema",
  "type": "object",
  "properties": {
    "objects": {
      "type": "object",
      "additionalProperties": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer"
          },
          "name": {
            "type": "string                }
          }
        },
        "required": [
          "id",
          "name"
        ]
      }
    }
  }
}

我在上面的答案中省略了内部的 "additionalProperties": false,因为我发现使用该关键字会导致更多问题而不是解决问题,但如果您希望验证在内部对象具有除“name”和“id”以外的属性时失败,则这是使用该关键字的有效方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,