addict icon indicating copy to clipboard operation
addict copied to clipboard

implement json converter and representation

Open fmigneault opened this issue 3 years ago • 1 comments

Hi, First, I would like to say thanks for this amazing library! Very useful.

While developing on some of my projects, I came across a few times into situations where the convenience offered by this library was taken away because it was tedious to ensure JSON serializable items deeply nested in the definitions.

To resolve this, I came across the approach presented in this PR. I would like to contribute it. There are 2 additions:

  • method json that specifically ask the Dict (or its derived class) to call JSON conversion. This is a bit similar to to_dict method, but specifically looks for json method or properly in nested items. This method name is often employed, for example, in requests library items, pyramid, flask and many others. It also enforces str conversion of un-serializable items, such that the generated content is valid for json.dumps use. Any sub-class not directly JSON serializable only needs to implement json and will automatically benefit from the resolution.

  • method __repr__ combined with __json__ option. When activated, the representation of the Dict will be a "pretty print" representation (as JSON) of the contents. The module and name of the class is also displayed before the JSON representation to indicate it was a Dict or derived class.

I'm also open to further improvements if needed. Feedback welcomed.

fmigneault avatar May 01 '21 02:05 fmigneault

Coverage Status

Coverage remained the same at 100.0% when pulling 31f07b89795468e95dd929ca14ed55bc69b05a34 on fmigneault:json into 75284f9593dfb929cadd900aff9e35e7c7aec54b on mewwts:master.

coveralls avatar May 01 '21 02:05 coveralls