Hide keyboard shortcuts

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# This file is part of daf_butler. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (http://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 <http://www.gnu.org/licenses/>. 

21 

22from __future__ import annotations 

23 

24__all__ = ("JsonFormatter", ) 

25 

26import builtins 

27import json 

28 

29from typing import ( 

30 TYPE_CHECKING, 

31 Any, 

32 Optional, 

33 Type, 

34) 

35 

36from .file import FileFormatter 

37 

38if TYPE_CHECKING: 38 ↛ 39line 38 didn't jump to line 39, because the condition on line 38 was never true

39 from lsst.daf.butler import StorageClass 

40 

41 

42class JsonFormatter(FileFormatter): 

43 """Interface for reading and writing Python objects to and from JSON files. 

44 """ 

45 extension = ".json" 

46 

47 unsupportedParameters = None 

48 """This formatter does not support any parameters (`frozenset`)""" 

49 

50 def _readFile(self, path: str, pytype: Optional[Type[Any]] = None) -> Any: 

51 """Read a file from the path in JSON format. 

52 

53 Parameters 

54 ---------- 

55 path : `str` 

56 Path to use to open JSON format file. 

57 pytype : `class`, optional 

58 Not used by this implementation. 

59 

60 Returns 

61 ------- 

62 data : `object` 

63 Data as Python object read from JSON file. 

64 """ 

65 with open(path, "rb") as fd: 

66 data = self._fromBytes(fd.read(), pytype) 

67 

68 return data 

69 

70 def _writeFile(self, inMemoryDataset: Any) -> None: 

71 """Write the in memory dataset to file on disk. 

72 

73 Will look for `_asdict()` method to aid JSON serialization, following 

74 the approach of the simplejson module. 

75 

76 Parameters 

77 ---------- 

78 inMemoryDataset : `object` 

79 Object to serialize. 

80 

81 Raises 

82 ------ 

83 Exception 

84 The file could not be written. 

85 """ 

86 with open(self.fileDescriptor.location.path, "wb") as fd: 

87 fd.write(self._toBytes(inMemoryDataset)) 

88 

89 def _fromBytes(self, serializedDataset: bytes, pytype: Optional[Type[Any]] = None) -> Any: 

90 """Read the bytes object as a python object. 

91 

92 Parameters 

93 ---------- 

94 serializedDataset : `bytes` 

95 Bytes object to unserialize. 

96 pytype : `class`, optional 

97 Not used by this implementation. 

98 

99 Returns 

100 ------- 

101 inMemoryDataset : `object` 

102 The requested data as a Python object or None if the string could 

103 not be read. 

104 """ 

105 try: 

106 data = json.loads(serializedDataset) 

107 except json.JSONDecodeError: 

108 data = None 

109 

110 return data 

111 

112 def _toBytes(self, inMemoryDataset: Any) -> bytes: 

113 """Write the in memory dataset to a bytestring. 

114 

115 Parameters 

116 ---------- 

117 inMemoryDataset : `object` 

118 Object to serialize 

119 

120 Returns 

121 ------- 

122 serializedDataset : `bytes` 

123 bytes representing the serialized dataset. 

124 

125 Raises 

126 ------ 

127 Exception 

128 The object could not be serialized. 

129 """ 

130 if hasattr(inMemoryDataset, "_asdict"): 

131 inMemoryDataset = inMemoryDataset._asdict() 

132 return json.dumps(inMemoryDataset, ensure_ascii=False).encode() 

133 

134 def _coerceType(self, inMemoryDataset: Any, storageClass: StorageClass, 

135 pytype: Optional[Type[Any]] = None) -> Any: 

136 """Coerce the supplied inMemoryDataset to type `pytype`. 

137 

138 Parameters 

139 ---------- 

140 inMemoryDataset : `object` 

141 Object to coerce to expected type. 

142 storageClass : `StorageClass` 

143 StorageClass associated with `inMemoryDataset`. 

144 pytype : `type`, optional 

145 Override type to use for conversion. 

146 

147 Returns 

148 ------- 

149 inMemoryDataset : `object` 

150 Object of expected type `pytype`. 

151 """ 

152 if inMemoryDataset is not None and pytype is not None and not hasattr(builtins, pytype.__name__): 

153 if storageClass.isComposite(): 153 ↛ 155line 153 didn't jump to line 155, because the condition on line 153 was never false

154 inMemoryDataset = storageClass.delegate().assemble(inMemoryDataset, pytype=pytype) 

155 elif not isinstance(inMemoryDataset, pytype): 

156 # Hope that we can pass the arguments in directly 

157 inMemoryDataset = pytype(inMemoryDataset) 

158 return inMemoryDataset