首页 文章

如何从json模式中的值获取类型引用

提问于
浏览
0

我有一个json架构,我有3种类型的媒体, Headers ,图像和头像 .

每种媒体类型都有不同的结构,所以我使用 $refoneOf 来指定哪些是有效选项 .

但是,我无法弄清楚如何根据兄弟的值来指定使用哪个引用 .

我的架构看起来像这样

const mediaSchema = {
    "type": "object",
    "required": ["mediaType", "content", "points"],
    "properties":{
        "mediaType": {"type":"string", "pattern": "^(image|avatar|caption)$"},
        "content": {
            "oneOf": [
                {"$ref":"#/definitions/image"},
                {"$ref": "#/definitions/caption"},
                {"$ref": "#/definitions/avatar"}
            ],
        }
    },
    "definitions": {
        "caption": 
            {"type": "object",
                "required": ["text"],
                "properties": {
                    "text": {"type": "string"},
                    "fontSize": {"type": "string", "pattern": "^[0-9]{1,3}px$"}
            }
        },
        "image": {"type": "string", "format": "url"},
        "avatar": 
            {"type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "image": {"type": "string", "format":"url"}
            }
        }
    }
}

当我定义一个像你的头像

mediaItem = {
    "mediaType":"avatar",
    "content": {
         "name": "user name",
         "avatar": "https://urlToImage
     }
}

它应该是有效的,但如果我将头像定义为

mediaItem = {
    "mediaType": "avatar",
    "content": "https://urlToImage"
}

它应该抛出一个错误,因为它对于媒体类型的头像无效 .

1 回答

  • 1

    你是在正确的轨道上,但你应该将oneOf调度程序放到模式的根目录,并将 "content" 定义为3个独立的常量作为鉴别器,如下所示:

    {
        "oneOf": [
            {
                "type": "object",
                "properties": {
                    "mediaType": {
                        "const": "avatar"
                    },
                    "content": { "$ref": "#/definitions/avatar" }
                },
                "required": ["mediaType", "content"]
            },
            // ...
        ],
        "definitions": {
            // ...
        }
    }
    

    注意: "const" 关键字仅存在于最新版本的json schema(draft6)中 . 您使用的验证器实现可能还不支持它 . 在这种情况下,你可以用 "enum": ["avatar"] 这样的单元素枚举替换 "const": "avatar"

相关问题