How to tell JSON schema validator to pick schema from property value?

后端 未结 2 926
温柔的废话
温柔的废话 2020-12-06 11:06

For example a schema for a file system, directory contains a list of files. The schema consists of the specification of file, next a sub type \"image\" and another one \"tex

相关标签:
2条回答
  • 2020-12-06 11:34

    I think cloudfeet answer is a valid solution. You could also use the same approach described here.

    You would have a file object type which could be "anyOf" all the subtypes you want to define. You would use an enum in order to be able to reference and validate against each of the subtypes.

    If the sub-types schemas are in the same Json-Schema file you don't need to reference the uri explicitly with the "$ref". A correct draft4 validator will find the enum value and will try to validate against that "subschema" in the Json-Schema tree.

    In draft5 (in progress) a "switch" statement has been proposed, which will allow to express alternatives in a more explicit way.

    0 讨论(0)
  • 2020-12-06 11:35

    The validation parts of JSON Schema alone cannot do this - it represents a fixed structure. What you want requires resolving/referencing schemas at validation-time.

    However, you can express this using JSON Hyper-Schema, and a rel="describedby" link:

    {
        "title": "Directory entry",
        "type": "object",
        "properties": {
            "fileType": {"type": "string", "format": "uri"}
        },
        "links": [{
            "rel": "describedby",
            "href": "{+fileType}"
        }]
    }
    

    So here, it takes the value from "fileType" and uses it to calculate a link with relation "describedby" - which means "the schema at this location also describes the current data".

    The problem is that most validators do not take any notice of any links (including "describedby" ones). You need to find a "hyper-validator" that does.

    UPDATE: the tv4 library has added this as a feature

    0 讨论(0)
提交回复
热议问题