繁体   English   中英

如何验证值是否与数据类型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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM