s-knibbs / dataclasses-jsonschema

JSON schema generation from dataclasses
MIT License
166 stars 38 forks source link

Optional object is not working #167

Closed thanakijwanavit closed 2 years ago

thanakijwanavit commented 3 years ago

optional object is not working for example

@dataclass
class TestSubData(JsonSchemaMixin):
  a: int = 0 

@dataclass
class TestData(JsonSchemaMixin):
  subData: Optional[TestSubData] = None

the schema i got is

$schema: http://json-schema.org/draft-06/schema#
definitions:
  TestSubData:
    description: 'TestSubData(a: int = 0)'
    properties:
      a:
        default: 0
        type: integer
    type: object
description: 'TestData(subData: Union[__main__.TestSubData, NoneType] = None)'
properties:
  subData:
    $ref: '#/definitions/TestSubData'
type: object

you can see that {'subData':None} will be rejected eventhough it is a valid data according to the dataclass

thanakijwanavit commented 3 years ago

the correct output would be

$schema: http://json-schema.org/draft-06/schema#
definitions:
  TestSubData:
    description: 'TestSubData(a: int = 0)'
    properties:
      a:
        default: 0
        type: integer
    type: 
      - object
      - "null"
description: 'TestData(subData: Union[__main__.TestSubData, NoneType] = None)'
properties:
  subData:
    $ref: '#/definitions/TestSubData'
type: object
thanakijwanavit commented 3 years ago

thank you

s-knibbs commented 2 years ago

You can use Nullable[TestSubData] to allow nulls. It should give you something like:

$schema: http://json-schema.org/draft-06/schema#
definitions:
  TestSubData:
    description: 'TestSubData(a: int = 0)'
    properties:
      a:
        default: 0
        type: integer
    type: object
description: 'TestData(subData: Union[__main__.TestSubData, dataclasses_jsonschema.type_defs._NULL_TYPE]
  = None)'
properties:
  subData:
    oneOf:
    - $ref: '#/definitions/TestSubData'
    - type: 'null'
type: object