Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Path fields are not not JSON serializable #473

Closed
mikegoodspeed opened this issue Apr 14, 2019 · 1 comment

Comments

Projects
None yet
2 participants
@mikegoodspeed
Copy link
Contributor

commented Apr 14, 2019

Bug

  • OS: Ubuntu
  • Python version: 3.6.8
  • Pydantic version: 0.23

DirectoryPath is not json serializable.

import pydantic


class Model(pydantic.BaseModel):
    directory: pydantic.DirectoryPath


def test_directory_path_json():
    model = Model(directory="/")
    assert model.json() == '{"directory": "/"}'


if __name__ == "__main__":
    test_directory_path_json()
Traceback (most recent call last):
  File "<snip>/site-packages/pydantic/json.py", line 45, in pydantic_encoder
    encoder = ENCODERS_BY_TYPE[type(obj)]
KeyError: <class 'pathlib.PosixPath'>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "tests/test_pydantic.py", line 14, in <module>
    test_directory_path_json()
  File "tests/test_pydantic.py", line 10, in test_directory_path_json
    assert model.json() == '{"directory": "/"}'
  File "<snip>/site-packages/pydantic/main.py", line 312, in json
    **dumps_kwargs,
  File "<snip>/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "<snip>/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "<snip>/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "<snip>/site-packages/pydantic/json.py", line 47, in pydantic_encoder
    raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
TypeError: Object of type 'PosixPath' is not JSON serializable

This is fixed by adding the correct types to the ENCODERS_BY_TYPE dict.

import pathlib

import pydantic.json

pydantic.json.ENCODERS_BY_TYPE[pathlib.PosixPath] = str
pydantic.json.ENCODERS_BY_TYPE[pathlib.WindowsPath] = str
@samuelcolvin

This comment has been minimized.

Copy link
Owner

commented Apr 15, 2019

Thanks for reporting. PR welcome to fix this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.