![](/img/trans.png)
[英]How to Validate two JSON API Response key-value pair matches on runtime using python?
[英]How to validate that the value matches datatype 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應該只接受布爾值,而不能接受其他值或字符串。
到目前為止,我的代碼檢查“ .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
獲得datatype( data_type
)后,可以使用python內置方法isinstance
進行驗證。
value = your_json["XXX"]
if isinstance(value,data_type):
print "Correct"
else:
print "Data Types do not match"
檢查此鏈接python isinstance()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.