【问题标题】:Json-Schema: Multiple elements of same typeJson-Schema:相同类型的多个元素
【发布时间】:2014-11-05 20:15:42
【问题描述】:

我尝试为我的数据编写一个 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!"
        }
    ]
}

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

{
    "$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"
                    }
                }
            }
        }
    }
}

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

【问题讨论】:

    标签: json jsonschema


    【解决方案1】:

    是的,您可以通过 $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
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-17
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 1970-01-01
      • 2012-11-22
      相关资源
      最近更新 更多