JSON 架构描述对象键的值(当键是动态的时)



我有一个具有动态键名的对象,我想描述键可以具有的值模式,即:

{
   "properties": {
      "usersById": {
         "additionalProperties": {
            "properties": {
               "email": {
                  "type": "boolean"
               },
               "phone": {
                  "type": "boolean"
               },
               "address": {
                  "type": "boolean"
               }
            },
            "type": "object"
         },
         "type": "object"
      }
   },
   ...
}

这在我的验证步骤中似乎没有做任何事情(使用 AJV JS pkg(。我想限制为仅此模型架构:

{
  usersById: {
    '1234abcd': {
      email: true,
      phone: false,
      address: false,
    },
  },
}

您可以使用patternProperties,就像properties一样,但使用正则表达式。

https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-6.5.5

举个例子...

图式:

{
  "type": "object",
  "patternProperties": {
    "^S_": { "type": "string" },
    "^I_": { "type": "integer" }
  },
  "additionalProperties": false
}

有效实例:

{ "I_0": 42 }

无效实例:

{ "S_0": 42 }

从 https://json-schema.org/understanding-json-schema/reference/object.html#pattern-properties 中提升的示例

请注意,最好

记住这些正则表达式不是隐式锚定的,因此如果您需要锚定正则表达式,则需要锚定它们。

最新更新