Hi, The issue with custom types serialized/unserialized with JSON is that they don't exist in JSON format, so you need to find a way to represent it without breaking other types (like a prefix in a string or a specific JSON object with fields that identify its type). But they still don't exist in JSON and you usually want to parse real JSON, not over-interpreting objects that are contained in the document, so it's not a good idea to add custom types by default. The solution is to use custom encoders/decoders, and it's possible with Python json module (https://docs.python.org/3/library/json.html#encoders-and-decoders). So you just use it when you need custom types, and otherwise you don't have to deal with them. Le mer. 10 juin 2020 à 14:19, J. Pic <jpic@yourlabs.org> a écrit :
Hi all,
This is a proposal to enable uuid objects serialization / deserialization by the json module out of the box.
UUID objects cast to string:
example = uuid.uuid4() str(example) 'b8bcbfaa-d54f-4f33-9d7e-c91e38bb1b63'
The can be casted from string:
example == uuid.UUID(str(example)) True
But are not serializable out of the box:
json.dumps(example) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.8/json/__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "/usr/lib/python3.8/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/usr/lib/python3.8/json/encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type UUID is not JSON serializable
Wouldn't it be pythonically possible to make this work out of the box, without going through the string typecasting ?
If that discussion goes well perhaps we can also talk about datetimes ... I know there's nothing about datetime formats in the json specification, that users are free to choose, but could we choose a standard format by default that would just work for people who don't care about the format they want.
Thank you in advance for your replies
Have a great day
-- ∞ _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-leave@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/W23G6C... Code of Conduct: http://python.org/psf/codeofconduct/
-- Antoine Rozo