json-schema-org/understanding-json-schema

Set "required" in property definition

libook opened this issue · 4 comments

I didn't find information on the document. So I don't know whether it is exists.

Current usage for "required" command:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "required": [
        "name"
    ],
    "properties": {
        "name": {
            "type": "string"
        }
    }
}

When I want to remove the property "name", I should always remember removing "name" from "required" array.
It will be helpful if I can define "required" in the definition of properties. For example:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
        "name": {
            "type": "string",
            "isRequired": true
        }
    }
}

Please let me know if there are reasons we can not do like this.

required as part of the property definition is a pre-draft-04 feature. With draft-04 and later, required properties are declared using the required and giving it an array of property name strings, like you show in your first example.

I wouldn't even know where to look for a conversation about that decision. The https://github.com/json-schema-org/json-schema-spec issue list doesn't go back that far.

@handrews @Relequestual would either of you have information on this?

@gregsdennis That assumes there WAS a discussion. I simply don't know.
If there was, it might be somewhere here https://github.com/json-schema/json-schema/issues

Regardless, given the change was made ages ago, and the utility in the current method, we're not going to change this. Sorry.

There's legitimate use case for making something required without defining it in properties.

On a flip side, a linter could pick up and warn on this as an option / rule...