0
可以說我有一個包含這個文件:如何驗證值相匹配的數據類型的Python
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'
現在我有一個JSON文件,該文件是這樣的:
{
"XXX": -20,
"XYZ": 50
}
我如何驗證是否爲正確的名稱給出了正確的值/布爾值?例如,由於uint8,XXX應該只能允許正數,並且不能爲負數。儘管XYZ只能使用布爾值,而不能使用其他值或字符串。
到目前爲止,我的代碼檢查json文件中的「名稱」是否存在於「.txt」文件中,然後檢查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