40

I have a json document in which a part can be either null or a subobject, like this:

[{
    "owner":null    
},
{
    "owner":{
        "id":1
    }   
}]

The question is if its possible to model this in json schema draft v4 using ref?

What I would like is something like this

{
    "type":"object",
    "properties":{
        "owner":{
            "type":["null", "object"],
            "$ref":"#/definitions/id"
        }
    },
    "definitions":{
        "id":{
            "type":"object",
            "properties":{
                "id":{
                    "type":"number"
                }
            }
        } 
    }
}
viblo
  • 4,159
  • 4
  • 20
  • 28

3 Answers3

68

What you've posted should work, if you remove the "type":"object" from the definition.

However, a neater, more explicit way to specify alternatives is to use oneOf. You can keep your "id" definition untouched, and just use:

    "owner":{
        "oneOf": [
            {"type": "null"},
            {"$ref":"#/definitions/id"}
        ]
    }
cloudfeet
  • 12,156
  • 1
  • 56
  • 57
  • Note: The `oneOf` keyword was introduced in [OpenAPI 3.0](https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/) and is not available in OpenAPI/Swagger 2.0. There is no support for "null" in OpenAPI 2.0, see this [SO answer](https://stackoverflow.com/questions/48111459/how-to-define-a-property-that-can-be-string-or-null-in-openapi-swagger). – Demitri Feb 20 '19 at 19:48
  • @Demitri true, but this question is about JSON Schema itself, not its OpenAPI flavor. – Helen Jun 09 '20 at 13:28
  • @Helen Fair point; I had tunnel vision when I was investigating an issue. Given the overlap, hopefully the comment helps someone. – Demitri Jun 09 '20 at 16:45
3

nullable field will be supported in OpenApi (aka Swagger) Specification v3.0.0

So with this new spec your definition would look like:

"properties":{
    "owner":{
        "nullable": true,
         ...
    }
},
Naz
  • 5,104
  • 8
  • 39
  • 63
1

I would suggest using:

"owner": {
  "nullable": true,
  "allOf": [{ "$ref":"#/definitions/id" }]
}

In ReDoc you will see than pretty: enter image description here

Instead of (object) or any using unsupported {"type": "null"} with oneOf.


Or even better - make a new nullable id type: { "$ref":"#/definitions/id-nullable" }

ZiiMakc
  • 31,187
  • 24
  • 65
  • 105