Json-Schema:相同类型的多个元素

Ole*_*ers 3 json jsonschema

我尝试为我的数据编写一个 json 模式。数据看起来是这样的:

{
    "gold": [
        {
            "id": "goldOne",
            "name": "firstGold",
            "title": "Gold 1 earned"
        },
        {
            "id": "goldTwo",
            "name": "secondGold",
            "title": "Gold 2 earned"
        }
    ],
    "silver": [
        {
            "id": "silberOne",
            "name": "firstSilver",
            "title": "Silver!"
        }
    ],
    "bronze": [
        {
            "id": "bronzeOne",
            "name": "firstBronze",
            "title": "Bronze!"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我已经为“黄金”数组创建了架构:

{
    "$schema": "http://json-schema.org/draft-04/schema#",   
    "title" : "trophy descriptions",
    "type": "object",
    "properties": {
        gold: {
            "description": "gold trophies",
            "type":"array",
            "items": {
                "type": "object",
                "properties": {
                    "id": {
                        "type": "string",
                        "description": "unique identifier"
                    },
                    "name": {
                        "type": "string",
                        "description": "label of trophy"
                    },
                    "title": {
                        "type": "string",
                        "description": "description of trophy"
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

因为“silver”和“bronze”数组包含与“gold”完全相同类型的元素,我想知道我是否必须写三遍相同的东西,或者我是否可以参考一个描述?

jru*_*ren 7

是的,您可以通过 $ref 关键字定义和引用模式:

{
    "$schema" : "http://json-schema.org/draft-04/schema#",
    "title" : "trophy descriptions",
    "type" : "object",
    "properties" : {
        "gold" : {
            "$ref" : "#/definitions/medal"
        },
        "silver" : {
            "$ref" : "#/definitions/medal"
        },
        "bronze" : {
            "$ref" : "#/definitions/medal"
        }

    },

    "definitions" : {
        "medal" : {
            "type" : "array"
            // and whatever you want here
        }
    }
}
Run Code Online (Sandbox Code Playgroud)