Metaschema specifying required attribute for all properties

僤鯓⒐⒋嵵緔 提交于 2020-01-24 13:59:05

问题


I want to customize a metaschema such that all properties are required to have an additional attribute, for example, how could I require that all properties specify a "type"?

Then this schema should fail:

{
    "$schema": "http://json-schema.org/schema#",
    "title": "...",
    "description": "...",
    "type": "object",
    "properties": {
        "name": {
            "description": "..."
        }
    }
}

But this one should succeed:

{
    "$schema": "http://json-schema.org/schema#",
    "title": "...",
    "description": "...",
    "type": "object",
    "properties": {
        "name": {
            "description": "...",
            "type": "string"
        }
    }
}

回答1:


Unfortunately, writing meta-schemas is not easy. It's being worked on, but there's no good solution yet.

You would have to make a copy of the meta-schema you want to extend and then add "required": ["type"].

But, while we're here, maybe I can convince you not to do this. Making the type keyword required causes problems in some cases. Here are a few examples. https://github.com/json-schema/json-schema/issues/172#issuecomment-124214534

EDIT

After discussing this further, we found that this particular case doesn't have the problems we normally run into with extending meta-schemas because it doesn't need to be recursive. Here is an example of extending the draft-06 schema to include a new keyword called custom which is a boolean and is required only at the top level of a properties schema.

{
  "allOf": [
    { "$ref": "http://json-schema.org/draft-06/schema#" },
    {
      "properties": {
        "properties": {
          "patternProperties": {
            ".*": {
              "properties": {
                "custom": { "type": "boolean" }
              },
              "required": ["custom"]
            }
          }
        }
      }
    }
  ]
}

And here's an example schema that conforms to this meta-schema.

{
  "properties": {
    "foo": {
      "custom": true,
      "not": { "type": "string" }
    }
  }
}

The custom keyword is required for the "foo" schema, but not the not schema or the top level schema.



来源:https://stackoverflow.com/questions/51160774/metaschema-specifying-required-attribute-for-all-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!