简体   繁体   中英

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:

{
"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. While XYZ should only take in boolean and no other values or string.

So far my code checks if the "name" from json file exist in the ".txt" file and then I check what the DataType is.

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 .

value = your_json["XXX"]

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

Check this link python isinstance()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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