JSON Schema - require all properties

2020-02-08 10:00发布

The required field in JSON Schema

JSON Schema features the properties, required and additionalProperties fields. For example,

{
    "type": "object",
    "properties": {
        "elephant": {"type": "string"},
        "giraffe": {"type": "string"},
        "polarBear": {"type": "string"}
    },
    "required": [
        "elephant",
        "giraffe",
        "polarBear"
    ],
    "additionalProperties": false
}

Will validate JSON objects like:

{
    "elephant": "Johnny",
    "giraffe": "Jimmy",
    "polarBear": "George"
}

But will fail if the list of properties is not exactly elephant, giraffe, polarBear.

The problem

I often copy-paste the list of properties to the list of required, and suffer from annoying bugs when the lists don't match due to typos and other silly errors.

Is there a shorter way to denote that all properties are required, without explicitly naming them?

标签: jsonschema
3条回答
看我几分像从前
2楼-- · 2020-02-08 10:45

You can just use the "minProperties" property instead of explicity naming all the fields.

{
    "type": "object",
    "properties": {
        "elephant": {"type": "string"},
        "giraffe": {"type": "string"},
        "polarBear": {"type": "string"}
    },
    "additionalProperties": false,
    "minProperties": 3
}
查看更多
来,给爷笑一个
3楼-- · 2020-02-08 10:45

I doubt there exists a way to specify required properties other than explicitly name them in required array.

But if you encounter this issue very often I would suggest you to write a small script that post-process your json-schema and add automatically the required array for all defined objects.

The script just need to traverse the json-schema tree, and at each level, if a "properties" keyword is found, add a "required" keyword with all defined keys contained in properties at the same level.

Let the machines do the bore stuff.

查看更多
手持菜刀,她持情操
4楼-- · 2020-02-08 10:59

I do this in code with a one-liner, for instance, if I want to use required for insert in a DB, but only want to validate against the schema when performing an update.

prepareSchema(action) {
    const actionSchema = R.clone(schema)
    switch (action) {
        case 'insert':
            actionSchema.$id = `/${schema.$id}-Insert`
            actionSchema.required = Object.keys(schema.properties)
            return actionSchema
        default:
            return schema
    }
}
查看更多
登录 后发表回答