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

mikegoodspeed opened this issue Apr 14, 2019 · 1 comment

Path fields are not not JSON serializable #473

mikegoodspeed opened this issue Apr 14, 2019 · 1 comment


Copy link

@mikegoodspeed mikegoodspeed commented Apr 14, 2019


  • 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__":
Traceback (most recent call last):
  File "<snip>/site-packages/pydantic/", 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/", line 14, in <module>
  File "tests/", line 10, in test_directory_path_json
    assert model.json() == '{"directory": "/"}'
  File "<snip>/site-packages/pydantic/", line 312, in json
  File "<snip>/json/", line 238, in dumps
  File "<snip>/json/", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "<snip>/json/", line 257, in iterencode
    return _iterencode(o, 0)
  File "<snip>/site-packages/pydantic/", 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
Copy link

@samuelcolvin samuelcolvin 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
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
2 participants