8000 Path fields are not not JSON serializable · Issue #473 · pydantic/pydantic · GitHub
[go: up one dir, main page]

Skip to content

Path fields are not not JSON serializable #473

@mikegoodspeed

Description

@mikegoodspeed

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0