Skip to content

Can't parse_raw Optional[Json] generated from Pydantic #1073

@volker48

Description

@volker48

Bug

Please complete:

  • OS: any
  • Python version import sys; print(sys.version):3.7.3 (default, Mar 27 2019, 09:23:15)
    [Clang 10.0.1 (clang-1001.0.46.3)]
  • Pydantic version import pydantic; print(pydantic.VERSION): 1.2

Where possible please include a self contained code snippet describing your bug:

from typing import Optional
from pydantic import Json, BaseModel

class Test(BaseModel):
    name: str
    some_obj: Optional[Json]

t = Test(name="hi")
serialized = t.json()
print(serialized)
t_deserialized = Test.parse_raw(serialized)

The above will fail with:

pydantic.error_wrappers.ValidationError: 1 validation error for Test
some_obj
  JSON object must be str, bytes or bytearray (type=type_error.json)

Because serialized is JSON that takes the following form: {"name": "hi", "some_obj": null}. If the some_obj key is omitted entirely everything works fine.

I would expect parse_raw() to work with the output of json().

The crux of the issue seems to be that validation will fail if an Optional[Json] field is present, but has a value of None. This will also fail Test(name='foo', some_obj=None).

This example works fine in pydantic < 1.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V1Bug related to Pydantic V1.X

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions