首页 > 解决方案 > json-schema 描述对象键的值(当键是动态的时)

问题描述

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

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

标签: jsonschemajson-schema-validator

解决方案


您可以使用patternPropertieswhich is likeproperties但您使用的是正则表达式。

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

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


推荐阅读