dataclasses-json icon indicating copy to clipboard operation
dataclasses-json copied to clipboard

wider config scopes

Open lidatong opened this issue 5 years ago • 3 comments

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

lidatong avatar Sep 07 '19 17:09 lidatong

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

MichaelAzimov avatar Apr 28 '20 17:04 MichaelAzimov

@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

lidatong avatar Jun 06 '20 15:06 lidatong

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

powellnorma avatar Apr 21 '23 16:04 powellnorma