-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Closed
Labels
Description
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 serializableThis 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] = strpilosus, haizaar, Querela and gitttt