【问题标题】:json-schema describe object key's values (when keys are dynamic)json-schema 描述对象键的值(当键是动态的时)
【发布时间】:2019-06-19 15:21:11
【问题描述】:

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

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

【问题讨论】:

    标签: jsonschema json-schema-validator


    【解决方案1】:

    您可以使用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

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

    【讨论】:

    猜你喜欢
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 2013-07-12
    • 2018-01-05
    • 2021-05-21
    • 1970-01-01
    相关资源
    最近更新 更多