lidatong / dataclasses-json

Easily serialize Data Classes to and from JSON
MIT License
1.39k stars 154 forks source link

wider config scopes #139

Open lidatong opened 5 years ago

lidatong commented 5 years ago

Sharing encoder / decoder in wider scopes (currently must be per-field. type, class, global are all potential scopes)

MichaelAzimov commented 4 years ago

Is this issue up-for-grabs? I would love to tackle this, because it would really help my use case

lidatong commented 4 years ago

@MichaelAzimov sorry for not getting back to you on this. There currently is undocumented global config functionality (mainly because it's pretty experimental). For example:

from datetime import date
import dataclasses_json.cfg

dataclasses_json.cfg.global_config.encoders[date] = date.isoformat
dataclasses_json.cfg.global_config.decoders[date] = date.fromisoformat
powellnorma commented 1 year ago

Note: In case you have an optional field like day: date|None, you have to add:

dataclasses_json.cfg.global_config.encoders[date|None] = lambda x: x and date.isoformat(x)

otherwise you still get the TypeError: Object of type date is not JSON serializable exception