JSONSchema和验证子对象属性

时间:2017-10-27 13:15:24

标签: javascript json jsonschema

给定这个JSON对象:

names

这是一个包含子对象的对象,其中每个子对象具有相同的结构 - 它们都是相同的类型。每个子对象都是唯一键控的,因此它就像命名数组一样。

我想验证{ "objects": { "foo": { "id": 1, "name": "Foo" }, "bar": { "id": 2, "name": "Bar" } } } 属性中的每个对象是否针对JSON Schema引用进行验证。

如果objects属性是数组,例如:

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

是否可以做类似的事情,但是使用嵌套对象?

谢谢!

2 个答案:

答案 0 :(得分:3)

您可以尝试这样的事情:

{
  "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"
          ]
        }
      }
    }
  }
}

答案 1 :(得分:1)

上述答案适用于将对象属性名称限制为小写字母。如果您不需要限制属性名称,那么这更简单:

{
  "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"。