Transform object making it suitable for json serialization.
(obj,
builtin_types=(numbers.Real, str), key=None,
keyfilter=None,
unknown_type_filter=None)
| 231 | |
| 232 | |
| 233 | def jsonify(obj, |
| 234 | builtin_types=(numbers.Real, str), key=None, |
| 235 | keyfilter=None, |
| 236 | unknown_type_filter=None): |
| 237 | """Transform object making it suitable for json serialization.""" |
| 238 | from kombu.abstract import Object as KombuDictType |
| 239 | _jsonify = partial(jsonify, builtin_types=builtin_types, key=key, |
| 240 | keyfilter=keyfilter, |
| 241 | unknown_type_filter=unknown_type_filter) |
| 242 | |
| 243 | if isinstance(obj, KombuDictType): |
| 244 | obj = obj.as_dict(recurse=True) |
| 245 | |
| 246 | if obj is None or isinstance(obj, builtin_types): |
| 247 | return obj |
| 248 | elif isinstance(obj, (tuple, list)): |
| 249 | return [_jsonify(v) for v in obj] |
| 250 | elif isinstance(obj, dict): |
| 251 | return { |
| 252 | k: _jsonify(v, key=k) for k, v in obj.items() |
| 253 | if (keyfilter(k) if keyfilter else 1) |
| 254 | } |
| 255 | elif isinstance(obj, (datetime.date, datetime.time)): |
| 256 | return _datetime_to_json(obj) |
| 257 | elif isinstance(obj, datetime.timedelta): |
| 258 | return str(obj) |
| 259 | else: |
| 260 | if unknown_type_filter is None: |
| 261 | raise ValueError( |
| 262 | f'Unsupported type: {type(obj)!r} {obj!r} (parent: {key})' |
| 263 | ) |
| 264 | return unknown_type_filter(obj) |
| 265 | |
| 266 | |
| 267 | def raise_with_context(exc): |