diff options
| author | Rob van der Linde <rob@catalyst.net.nz> | 2023-05-16 12:00:56 +1200 |
|---|---|---|
| committer | Andrew Bartlett <abartlet@samba.org> | 2023-06-25 23:29:32 +0000 |
| commit | d01cd64da23bb092c63ef7a2ff57d83c6b4e76e8 (patch) | |
| tree | 839f3affe2e902711c0481cb17f0fb71c7d3b12a /python | |
| parent | 1a5184e404d602e389b96535e792fc77314f1fd4 (diff) | |
| download | samba-d01cd64da23bb092c63ef7a2ff57d83c6b4e76e8.tar.gz samba-d01cd64da23bb092c63ef7a2ff57d83c6b4e76e8.tar.bz2 samba-d01cd64da23bb092c63ef7a2ff57d83c6b4e76e8.zip | |
netcmd: add custom json encoder for object type fields
The custom JSONEncoder class is also capable of encoding Dn objects to
str, and any object that has a __json__ method.
The __json__ method is not an official dunder method, but this has
been used by other frameworks too (like Pyramid).
Signed-off-by: Rob van der Linde <rob@catalyst.net.nz>
Reviewed-by: Andrew Bartlett <abartlet@samba.org>
Reviewed-by: Joseph Sutton <josephsutton@catalyst.net.nz>
Diffstat (limited to 'python')
| -rw-r--r-- | python/samba/netcmd/encoders.py | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/python/samba/netcmd/encoders.py b/python/samba/netcmd/encoders.py new file mode 100644 index 00000000000..7d32b683acc --- /dev/null +++ b/python/samba/netcmd/encoders.py @@ -0,0 +1,49 @@ +# Unix SMB/CIFS implementation. +# +# encoders: JSONEncoder class for dealing with object fields. +# +# Copyright (C) Catalyst.Net Ltd. 2023 +# +# Written by Rob van der Linde <rob@catalyst.net.nz> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# + +import json +from datetime import datetime +from decimal import Decimal +from enum import Enum + +from ldb import Dn + + +class JSONEncoder(json.JSONEncoder): + """Custom JSON encoder class to help out with some data types. + + For example, the json module has no idea how to encode a Dn object to str. + Another common object that is handled is Decimal types. + + In addition, any objects that have a __json__ method will get called. + """ + + def default(self, obj): + if isinstance(obj, (Decimal, Dn)): + return str(obj) + elif isinstance(obj, Enum): + return str(obj.value) + elif isinstance(obj, datetime): + return obj.isoformat() + elif getattr(obj, "__json__", None) and callable(obj.__json__): + return obj.__json__() + return obj |
