Home > other >  How to define dictionary whose values are showing of what type should be a property, which name is u
How to define dictionary whose values are showing of what type should be a property, which name is u

Time:09-17

I am working on application, which should verify a JSON. The properties are of different types (numeric, string, date), that is why I have not only to verify the presence of the properties, but also whether their value is of the required type.

That is why I would like to define dictionary, which key will be the name of the property and the value will be the type, that this property should be of (with the operator isinstance or in some other way). But I do not know how to implement this in Python. Something like this:

map_of_property_to_classes: Dict[str, any]
class_name = map_of_property_to_classes["property_name"]
print(isinstance("property_name", class_name))

Can somebody give a hint?

CodePudding user response:

Are you looking for something like the below?

from typing import Dict


def validate(data: Dict, meta_data: Dict) -> None:
    for k, v in data.items():
        if isinstance(v, meta_data[k]):
            print('OK')
        else:
            print(f'{v} must be of type {meta_data[k]}')


_data = {'x': 12, 'name': 12}
_meta_data = {'x': int, 'name': str}
validate(_data,_meta_data)

output

OK
12 must be of type <class 'str'>

CodePudding user response:

I'm not sure if this answer your question but I have written a script which read a JSON file and return a dict.

Here's the JSON file:

"Config":{
    "programming_languages" : {"_type" : "dict", "value" :  {
      "py"    : "python",
      "js"    : "javascript",
      "txt"   : "plain",
      "md"      : "markdown",
      "cs"      : "csharp"
    }},
    "noEditTypes": {"_type" : "set", "value" : ["pdf", "jpg", "jpeg", "png"]}
}

And here's the python Code:

@staticmethod
def configParser():
    with open("data/data.json", "r") as f:
        data = json.load(f).get("Config")
        outData = {}
        for i in data:
            valTypeName = data[i].get("_type")
            if valTypeName == "set":
                valType = set
            elif valTypeName == "str":
                valType = str
            elif valTypeName == "int":
                valType = int
            elif valTypeName == "list":
                valType = list
            elif valTypeName == "dict":
                valType = dict
            else:
                raise Exception("Unknown Type: {}".format(valTypeName))
            valvalue = data[i].get("value")

            outData[i] = valType(valvalue)
    return outData

I think if you modify this code a bit it would also work for your intended use.

  • Related