我正在努力寻找一个通用函数来将变量转换为其他类型,其中类型作为参数提供,就像astype
用于numpy数组一样。
上下文:我正在构建Flask API,并且我想根据以下条件来验证输入JSON正文:
示例代码来阐明我的问题:
import numpy as np
def checkValue(data, key, value_type, default_value):
'''
data: dict which is validated
key: key and accompanied value to check
value_type: type should match value_type. If not, try to convert or return default_value
default_value: if empty or conversion fails, return default_value
'''
if key not in data.keys():
return(default_value)
elif type(data[key]) != value_type:
try:
# This part should be easier:
tmp_array = np.array(data[key])
tmp_array = tmp_array.astype(value_type)
return(np.asscalar(tmp_array))
except Exception as err:
return(default_value)
else:
return(data[key])
x = {
'a': '1123',
'b': 'hello'
}
x['a'] = checkValue(x, 'a', 'int', 1000) # x['a'] = 1123
x['b'] = checkValue(x, 'b', 'int', 1000) # x['b'] = 1000
x['c'] = checkValue(x, 'c', 'str', 'hello') # x['c'] = 'hello'