如何验证该值是否与数据类型Python匹配

时间:2016-04-03 09:38:41

标签: python json

假设我有一个包含此文件的文件:

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
}

如何验证是否为正确的名称指定了正确的值/布尔值?例如,XXX应该只能由于uint8而允许正数而且没有负数。虽然XYZ应该只接受布尔值而没有其他值或字符串。

到目前为止,我的代码检查json文件中的“name”是否存在于“.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

1 个答案:

答案 0 :(得分:1)

获得数据类型(data_type)后,可以使用python内置方法isinstance进行验证。

value = your_json["XXX"]

if isinstance(value,data_type):
    print "Correct"
else:
    print "Data Types do not match"

点击此链接python isinstance()