comparison sat/tools/common/data_format.py @ 2697:fcc945537d5f

tools (common/data_format): serialise now check types and return a default value when empty string is parsed.
author Goffi <goffi@goffi.org>
date Sat, 01 Dec 2018 09:59:48 +0100
parents 8cacf7929f3c
children 46f2733a2a9b
comparison
equal deleted inserted replaced
2696:5849dcaab99d 2697:fcc945537d5f
131 131
132 @return(unicode): serialised data, can be transmitted as string to the bridge 132 @return(unicode): serialised data, can be transmitted as string to the bridge
133 """ 133 """
134 return json.dumps(data, ensure_ascii=False) 134 return json.dumps(data, ensure_ascii=False)
135 135
136 def deserialise(serialised_data): 136 def deserialise(serialised_data, default=None, type_check=dict):
137 """Deserialize data from bridge 137 """Deserialize data from bridge
138 138
139 @param serialised_data(unicode): data to deserialise 139 @param serialised_data(unicode): data to deserialise
140 @default (object): value to use when serialised data is empty string
141 @param type_check(type): if not None, the deserialised data must be of this type
140 @return(object): deserialised data 142 @return(object): deserialised data
143 @raise ValueError: serialised_data is of wrong type
141 """ 144 """
142 return json.loads(serialised_data) 145 if serialised_data == u"":
146 return default
147 ret = json.loads(serialised_data)
148 if type_check is not None and not isinstance(ret, type_check):
149 raise ValueError(u"Bad data type, was expecting {type_check}, got {real_type}"
150 .format(type_check=type_check, real_type=type(ret)))
151 return ret