[英]How to validate that the value matches datatype Python
Lets say I have a file which contains this: 可以说我有一个包含以下内容的文件:
XXX = Name;
XXX.Value = 15;
XXX.DataType = 'uint8';
YYY = Name;
YYY.Value = -50;
YYY.DataType = 'sint8';
YYY = Name;
ZZZ.Value = 123.123;
ZZZ.DataType = 'float'
XYZ = Name;
XYZ.Value = true;
XYZ.DataType = 'boolean'
Now I have a json file which looks like this: 现在我有一个看起来像这样的json文件:
{
"XXX": -20,
"XYZ": 50
}
How do I validate that the correct value/boolean is given for the correct name? 如何验证为正确的名称指定了正确的值/布尔值? For example XXX should only be able to allow positive numbers due to uint8 and no negative.
例如,由于uint8,XXX应该只能允许使用正数,而不能使用负数。 While XYZ should only take in boolean and no other values or string.
而XYZ应该只接受布尔值,而不能接受其他值或字符串。
So far my code checks if the "name" from json file exist in the ".txt" file and then I check what the DataType is. 到目前为止,我的代码检查“ .txt”文件中是否存在json文件中的“名称”,然后检查什么是DataType。
jdata = json.loads(open("test.json").read())
for root, dirs, files in os.walk(directory):
for key, value in jdata.iteritems():
for file in files:
with open(os.path.join(root, file)) as fle:
content = fle.read()
if file.endswith('.txt') and key in content:
re.search(regexDataType(key), content)
print "Name", key, "found in ", file
tt = re.search(regexDataType(key), content)
print tt.group(2) #Here I get the datatype for the specific "name" from Json file.
#How do I move on from here? How do I validate the value from json file is the correct one?
else:
print "Name", key, "not found in file", file
After you get the datatype( data_type
), you can verify by using python inbuilt method isinstance
. 获得datatype(
data_type
)后,可以使用python内置方法isinstance
进行验证。
value = your_json["XXX"]
if isinstance(value,data_type):
print "Correct"
else:
print "Data Types do not match"
Check this link python isinstance() 检查此链接python isinstance()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.