如何告诉JSON模式验证器从属性值中选择模式?

red*_*ben 11 inheritance json jsonschema

例如,文件系统的模式,目录包含文件列表.该模式包括文件的规范,接下来是子类型"图像"和另一个"文本".

底部有主目录模式.目录具有属性内容,该属性内容是应该是文件的子类型的项目数组.

基本上我正在寻找的是一种告诉验证器从被验证的json对象中的属性中查找"$ ref"的值的方法.

示例json:

{
    "name":"A directory",
    "content":[
        {
            "fileType":"http://x.y.z/fs-schema.json#definitions/image",
            "name":"an-image.png",
            "width":1024,
            "height":800
        }
        {
            "fileType":"http://x.y.z/fs-schema.json#definitions/text",
            "name":"readme.txt",
            "lineCount":101
        }
        {
            "fileType":"http://x.y.z/extended-fs-schema-video.json",
            "name":"demo.mp4",
            "hd":true
        }

    ]
}
Run Code Online (Sandbox Code Playgroud)

"伪"架构注意到"图像"和"文本"定义包含在同一模式中,但它们可能在别处定义

{
    "id": "http://x.y.z/fs-schema.json",
    "definitions": {
        "file": {
            "type": "object",
            "properties": {
                "name": { "type": "string" },
                "fileType": {
                    "type": "string",
                    "format": "uri"
                }
            }
        },
        "image": {
            "allOf": [
            { "$ref": "#definitions/file" },
            {
                "properties": {
                    "width": { "type": "integer" },
                    "height": { "type": "integer"}
                }
            }
            ]
        },
        "text": {
            "allOf": [
            { "$ref": "#definitions/file" },
            { "properties": { "lineCount": { "type": "integer"}}}
            ]
        }
    },
    "type": "object",
    "properties": {
        "name": { "type": "string"},
        "content": {
            "type": "array",
            "items": {
                "allOf": [
                { "$ref": "#definitions/file" },
                { *"$refFromProperty"*: "fileType" } // the magic thing
                ]
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

clo*_*eet 10

单独的JSON Schema的验证部分不能这样做 - 它代表一个固定的结构.您想要什么需要在验证时解析/引用模式.

但是,您可以使用JSON Hyper-Schema和rel="describedby"链接表达:

{
    "title": "Directory entry",
    "type": "object",
    "properties": {
        "fileType": {"type": "string", "format": "uri"}
    },
    "links": [{
        "rel": "describedby",
        "href": "{+fileType}"
    }]
}
Run Code Online (Sandbox Code Playgroud)

所以在这里,它从中获取值"fileType"并使用它来计算具有"describeby"关系的链接 - 这意味着"此位置的模式也描述了当前数据".

问题是大多数验证者都没有注意到任何链接(包括"由"描述的链接).你需要找到一个"超验证器".

更新:tv4库已添加此功能