ctdb-failover: Split statd_callout add-client/del-client
[Samba.git] / python / samba / netcmd / encoders.py
blob87f90a57a5dd795c05466dc5baebf3082ff8f6a6
1 # Unix SMB/CIFS implementation.
3 # encoders: JSONEncoder class for dealing with object fields.
5 # Copyright (C) Catalyst.Net Ltd. 2023
7 # Written by Rob van der Linde <rob@catalyst.net.nz>
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with this program. If not, see <http://www.gnu.org/licenses/>.
23 import json
24 from datetime import datetime
25 from decimal import Decimal
26 from enum import Enum
28 from ldb import Dn, MessageElement, Result
30 from samba.dcerpc.security import descriptor
33 class JSONEncoder(json.JSONEncoder):
34 """Custom JSON encoder class to help out with some data types.
36 For example, the json module has no idea how to encode a Dn object to str.
37 Another common object that is handled is Decimal types.
39 In addition, any objects that have a __json__ method will get called.
40 """
42 def default(self, obj):
43 if isinstance(obj, (Decimal, Dn, Exception, MessageElement)):
44 return str(obj)
45 if isinstance(obj, Result):
46 return obj.msgs
47 elif isinstance(obj, Enum):
48 return str(obj.value)
49 elif isinstance(obj, datetime):
50 return obj.isoformat()
51 elif isinstance(obj, descriptor):
52 return obj.as_sddl()
53 elif getattr(obj, "__json__", None) and callable(obj.__json__):
54 return obj.__json__()
55 return super().default(obj)