3

I'm trying to create a Json schema for an object. Is it possible to reference the top level root object, when defining an embedded object within it?

I've seen that I can reuse a definition through $ref:"#/definitions/..." but I am trying to reuse the whole top level object. Not just the properties within.

if my json looks like this:

{
    "name": "brodie",
    "age": 2,
    "bestFriend": {
        "name": "clara",
        "age": 4,
                "bestFriend": {
                       "name": "stella",
                       "age" : 5
                }
    }
}

I can create a json schema that looks like this:

{
"type": "object",
"properties": {
    "name": {
            "$ref": "#/definitions/name"
        },
        "age": {
            "$ref": "#/definitions/age"
        },
        "bestFriend": {
            "$ref": "#/definitions/bestFriend"


    },
},
    "definitions": {
        "name": {
            "type": "string"
        },
        "age": { 
            "type": "integer"
        },
        "bestFriend": {
            "type": "object",
            "allOf": [
                {"$ref": "#/defintions/name"},
                {"$ref": "#/definitions/age"},
                {"$ref": "#/definitions/bestFriend"}

            ]
        }
    }
}

But I'd like to do something like

{
    "type": "object",
    "title": "bestFriend",
    "properties": {
        "$ref": "#/definitions/bestFriend"
    },
    "definitions": {
        "name": {
            "type": "string"
        },
        "age": { 
            "type": "integer"
        },
        "bestFriend": {
            "type": "object",
            "allOf": [
                {"$ref": "#/defintions/name"},
                {"$ref": "#/definitions/age"},
                {"$ref": "#/definitions/bestFriend"}

            ]
        }
    }
}

I am using the same json object for all 3 instances brodie, clara, stella. I want to encapsulate the top level object as one definition so I can reference it later in a cleaner way. It would be nice if I didn't have the list of $refs at the top and only had them within the "definitions" object at the bottom. Is this even possible? Or is what I have above the recommended pattern.

(I know I could define some of these fields inline, but I plan on heavily reusing some json objects, and felt it would be cleaner if everything was defined in the "definitions" section.)

  • Possible duplicate of [JSON Schema - Recursive Schema Definition](https://stackoverflow.com/questions/20752716/json-schema-recursive-schema-definition) – jruizaranguren Sep 10 '19 at 08:41
  • Recursive json-schemas are allowed. Have a look at this answer: https://stackoverflow.com/questions/20752716/json-schema-recursive-schema-definition – jruizaranguren Sep 10 '19 at 08:42

0 Answers0