Skip to content

Commit a9e30b0

Browse files
committed
Handle nullable=true with oneOf and anyOf
- If `nullable=True` is alongside a `oneOf`/`anyOf` field, then add `{"type": "null"}` to the `oneOf`/`anyOf` arrray. - This activates only if there is no `type` field alongside the `oneOf` or `anyOf` field This helps ensure the resulting JSON Schema actually accepts null when using nullable with oneOf/anyOf
1 parent 13c01ce commit a9e30b0

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ about the problem.
3434
## Features
3535

3636
* converts OpenAPI 3.0 Schema Object to JSON Schema Draft 4
37-
* deletes `nullable` and adds `"null"` to `type` array if `nullable` is `true`
37+
* deletes `nullable` and adds `"null"` to `type` array if `nullable` is `true` and `type` is present
38+
* adds `{"type": "null"}` to `oneOf` or `anyOf` array if `nullable` is `true` and `type` is _not_ present
3839
* supports deep structures with nested `allOf`s etc.
3940
* removes [OpenAPI specific
4041
properties](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#fixed-fields-20)

openapi_schema_to_json_schema/to_jsonschema.py

+6
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,12 @@ def convertTypes(schema, options):
162162
toDateTime = options['dateToDateTime']
163163

164164
if schema.get('type') is None:
165+
# https://github.com/pglass/py-openapi-schema-to-json-schema/issues/10
166+
if schema.get('nullable') is True:
167+
for struct in ['oneOf', 'anyOf']:
168+
if struct in schema:
169+
schema[struct].append({'type': 'null'})
170+
165171
return schema
166172

167173
if (schema.get('type') == 'string' and schema.get('format') == 'date'

tests/to_jsonschema/test_nullable.py

+18
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,21 @@ def test_handles_nullable():
2323
"type": 'string'
2424
}
2525
assert result == expected
26+
27+
28+
def test_nullable_oneOf_anyOf():
29+
# https://github.com/pglass/py-openapi-schema-to-json-schema/issues/10
30+
for key in ['oneOf', 'anyOf']:
31+
schema = {
32+
key: [{"type": "string"}],
33+
"nullable": True,
34+
}
35+
result = convert(schema)
36+
expected = {
37+
"$schema": 'http://json-schema.org/draft-04/schema#',
38+
key: [
39+
{"type": "string"},
40+
{"type": "null"},
41+
]
42+
}
43+
assert result == expected

0 commit comments

Comments
 (0)