代码之家  ›  专栏  ›  技术社区  ›  pedalpete

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

  •  0
  • pedalpete  · 技术社区  · 9 年前

    我有一个json模式,我有3种媒体,标题,图像和化身。

    每种媒体类型都有不同的结构,所以我使用 $ref oneOf

    然而,我不知道如何根据同级的值指定要使用的引用。

    我的模式如下所示

    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 回复  |  直到 9 年前
        1
  •  1
  •   erosb    9 年前

    您已经走上了正确的道路,但应该将dispatcher之一放在模式的根目录下,并定义 "content" 用3个独立常数作为鉴别器,如下所示:

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

    注:the "const" 关键字仅存在于最新版本的json模式(draft6)中。您使用的验证器实现可能还不支持它。在这种情况下,您可以替换 "const": "avatar" "enum": ["avatar"]