Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""LICENSE
2Copyright 2019 Hermann Krumrey <hermann@krumreyh.com>
4This file is part of puffotter.
6puffotter is free software: you can redistribute it and/or modify
7it under the terms of the GNU General Public License as published by
8the Free Software Foundation, either version 3 of the License, or
9(at your option) any later version.
11puffotter is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
16You should have received a copy of the GNU General Public License
17along with puffotter. If not, see <http://www.gnu.org/licenses/>.
18LICENSE"""
21from typing import Dict, Any
24def jsonify_models(data: Dict[str, Any], deep: bool = True) -> Dict[str, Any]:
25 """
26 Serializes a dictionary and calls the __json__() method on all
27 objects that have one.
28 :param data: The data to serialize
29 :param deep: Indicates whether or not child models are included.
30 If False, only IDs will be included.
31 :return: The serialized data
32 """
33 to_jsonify = {}
34 for key, val in data.items():
35 to_jsonify[key] = _serialize(val, deep)
36 return to_jsonify
39def _serialize(obj: Any, deep: bool) -> Any:
40 """
41 Serializes an object, so that it can be jsonified without issues
42 :param obj: The object to serialize
43 :param deep: Indicates whether or not child models are included.
44 If False, only IDs will be included.
45 :return: The serialized object
46 """
47 if isinstance(obj, dict):
48 serialized_dict = {}
49 for key, val in obj.items():
50 serialized_dict[key] = _serialize(val, deep)
51 return serialized_dict
53 elif isinstance(obj, list):
54 serialized_list = []
55 for val in obj:
56 serialized_list.append(_serialize(val, deep))
57 return serialized_list
59 elif isinstance(obj, tuple):
60 return tuple(_serialize(list(obj), deep))
62 elif "__json__" in dir(obj):
63 return obj.__json__(deep)
64 else:
65 return obj