Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json-Schema: Multiple elements of same type

I try to write a json schema for my data. The data looks that way:

{
    "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!"
        }
    ]
}

I already created the schema for the "gold"-array:

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

Because the "silver" and "bronze" -arrays contain elements of the exact same type as "gold" I wonder if I have to write down the same stuff three times or if I can refer to a single description?

like image 469
Ole Albers Avatar asked Dec 14 '25 06:12

Ole Albers


1 Answers

Yes, you can define and reference schemas through $ref keyword:

{
    "$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
        }
    }
}
like image 146
jruizaranguren Avatar answered Dec 16 '25 22:12

jruizaranguren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!