Coverage for python/lsst/verify/jsonmixin.py: 30%
31 statements
« prev ^ index » next coverage.py v6.5.0, created at 2023-01-05 03:05 -0800
« prev ^ index » next coverage.py v6.5.0, created at 2023-01-05 03:05 -0800
1# This file is part of verify.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
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.
13#
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.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <https://www.gnu.org/licenses/>.
21__all__ = ['JsonSerializationMixin']
23import abc
24import json
27class JsonSerializationMixin(metaclass=abc.ABCMeta):
28 """Mixin that provides JSON serialization support to subclasses.
30 Subclasses must implement the `json` method. The method returns a `dict`
31 that can be serialized to JSON. Use the `jsonify_dict` method to handle
32 the conversion of iterables, numbers, strings, booleans and
33 `JsonSerializationMixin`-compatible objects into a JSON-serialiable object.
34 """
36 @abc.abstractproperty
37 def json(self):
38 """`dict` that can be serialized as semantic JSON, compatible with
39 the SQUASH metric service.
40 """
41 pass
43 @staticmethod
44 def jsonify_dict(d):
45 """Recursively build JSON-renderable objects on all values in a dict.
47 Parameters
48 ----------
49 d : `dict`
50 Dictionary to convert into a JSON-serializable object. Values
51 are recursively JSON-ified.
53 Returns
54 -------
55 json_dict : `dict`
56 Dictionary that can be serialized to JSON.
58 Examples
59 --------
60 Subclasses can use this method to prepare output in their `json`-method
61 implementation. For example::
63 def json(self):
64 return JsonSerializationMixin.jsonify_dict({
65 'value': self.value,
66 })
67 """
68 json_dict = {}
69 for k, v in d.items():
70 json_dict[k] = JsonSerializationMixin._jsonify_value(v)
71 return json_dict
73 @staticmethod
74 def _jsonify_list(lst):
75 """Recursively convert items of a list into JSON-serializable objects.
76 """
77 json_array = []
78 for v in lst:
79 json_array.append(JsonSerializationMixin._jsonify_value(v))
80 return json_array
82 @staticmethod
83 def _jsonify_value(v):
84 """Convert an object into a JSON-serizable object, recursively
85 processes dicts and iterables.
86 """
87 if isinstance(v, JsonSerializationMixin):
88 return v.json
89 elif isinstance(v, dict):
90 return JsonSerializationMixin.jsonify_dict(v)
91 elif isinstance(v, (list, tuple, set)):
92 return JsonSerializationMixin._jsonify_list(v)
93 else:
94 return v
96 def write_json(self, filepath):
97 """Write JSON to a file.
99 Parameters
100 ----------
101 filepath : `str`
102 Destination file name for JSON output.
103 """
104 with open(filepath, 'w') as outfile:
105 json.dump(self.json, outfile, sort_keys=True, indent=2)