ramonhagenaars / jsons

🐍 A Python lib for (de)serializing Python objects to/from JSON
https://jsons.readthedocs.io
MIT License
289 stars 41 forks source link

Add support for pathlib.Path objects #107

Closed alexmirrington closed 3 years ago

alexmirrington commented 4 years ago

The current default_object_deserializer does not support pathlib.Path objects. When trying to deserialise the string data/gqa to a pathlib.Path object, the default default_object_deserializer tries to access attributes of the string data/gqa, lesding to the following error in a dictionary comprehension:

Traceback (most recent call last):
  File "/home/alex/.virtualenvs/python-standard/lib/python3.8/site-packages/jsons/_load_impl.py", line 110, in _do_load
    result = deserializer(json_obj, cls, **kwargs)
  File "/home/alex/.virtualenvs/python-standard/lib/python3.8/site-packages/jsons/deserializers/default_object.py", line 40, in default_object_deserializer
    remaining_attrs = _get_remaining_args(obj, cls, constructor_args,
  File "/home/alex/.virtualenvs/python-standard/lib/python3.8/site-packages/jsons/deserializers/default_object.py", line 174, in _get_remaining_args
    remaining_attrs = {attr_name: obj[attr_name] for attr_name in obj
  File "/home/alex/.virtualenvs/python-standard/lib/python3.8/site-packages/jsons/deserializers/default_object.py", line 174, in <dictcomp>
    remaining_attrs = {attr_name: obj[attr_name] for attr_name in obj
TypeError: string indices must be integers

I would like to propose a default serialiser and deserialiser for pathlib.Path objects that allows for conversion between str and pathlib.Path. Whether to support a list of path segments like ["data", "gqa"] is up for discussion.

ramonhagenaars commented 4 years ago

Hi @alexmirrington . Thanks for the PR, I'll have a look.