dict2obj - Conversion tool for JSON structure to object
- Purpose:
This class module is used to convert a Python dictionary (
dict
) or JSON file into a object - where the dictionary’s key/value pairs become object attribute/value pairs.- Platform:
Linux/Windows | Python 3.6+
- Developer:
J Berendt
- Email:
- Comments:
Basic concept attribution.
- class dict2obj.Dict2Obj(*, dictionary=None, source='dict', filepath=None)[source]
Create a Python object from a standard Python dictionary, or JSON file.
- Parameters:
dictionary (dict, optional) – A standard Python dictionary where all key/value pairs will be converted into an object. Defaults to None.
source (str, optional) –
Source for the conversion. Defaults to ‘dict’.
’dict’: a standard Python dictionary
’json’: uses content from a JSON file
filepath (str, optional) – Full file path to the JSON file to be used. Defaults to None.
- Design:
A Python object is created from the passed dictionary (or JSON file), where each of the dictionary’s key/value pairs is turned into an object attribute/value pair.
- Note:
The dictionary or JSON file should be in a flat format. If a nested source is provided, the value of the object will be the nested structure. In other the object will not be nested.
This can be useful when loading a JSON config file into memory, as you can then access it like an object, rather than a dictionary.
- Example:
To convert a dictionary into an object:
>>> from utils4.dict2obj import Dict2Obj >>> d = dict(a=1, b=2, title='This is a title.') >>> obj = Dict2Obj(dictionary=d) >>> print(obj.title) This is a title.
- _VALID = ['dict', 'json']
- _create()[source]
Validate and create the object.
- Raises:
TypeError – If a key is not a string, or is a string yet begins with any type other than a string..
- _read_json() dict [source]
Read values from a JSON file into a dictionary.
- Returns:
A dictionary containing the JSON data.
- Return type:
dict
- _validate() bool [source]
Run the following validation tests:
The
source
value is valid.If ‘json’ source, a file path is provided.
If ‘json’ source, the provided file path exists.
- Returns:
True if all tests pass, otherwise False.
- Return type:
bool
- _validate_fileexists() bool [source]
Validation test: If a ‘json’ source, test the file path exists.
- Raises:
ValueError – If the passed filepath is not a ‘.json’ extension.
ValueError – If the passed filepath does not exist.
- Returns:
True if the source is ‘dict’; or if source is ‘json’ and the file exists, otherwise False.
- Return type:
bool
- _validate_is_dict() bool [source]
Validation test: Verify the object is a
dict
.- Raises:
TypeError – If the passed object is not a
dict
.- Returns:
True if the passed object is a
dict
.- Return type:
bool