json_data = {
"name": "Terminal",
"packageName": "application",
"order": 20,
"versionName": "1.37"
}
json_data.name() #result Terminal
json_data.order() #result 20
class Map(dict):
"""
Example:
m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
"""
def __init__(self, *args, **kwargs):
super(Map, self).__init__(*args, **kwargs)
for arg in args:
if isinstance(arg, dict):
for k, v in arg.items():
self[k] = v
if kwargs:
for k, v in kwargs.items():
self[k] = v
def __getattr__(self, attr):
return self.get(attr)
def __setattr__(self, key, value):
self.__setitem__(key, value)
def __setitem__(self, key, value):
super(Map, self).__setitem__(key, value)
self.__dict__.update({key: value})
def __delattr__(self, item):
self.__delitem__(item)
def __delitem__(self, key):
super(Map, self).__delitem__(key)
del self.__dict__[key]
>>> json_data = {
... "name": "Terminal",
... "packageName": "application",
... "order": 20,
... "versionName": "1.37"
... }
>>> data = Map(json_data)
>>> data.name
'Terminal'
>>> data.order
20
class Dict(dict):
def __new__(cls, *args, **kwargs):
self = dict.__new__(cls, *args, **kwargs)
self.__dict__ = self
return self
json_data = {
"name": "Terminal",
"packageName": "application",
"order": 20,
"versionName": "1.37"
}
a = Dict(json_data)
print(a.name)
print(a.packageName)
print(a.order)
print(a.versionName)
sergey@sergey-X55A:~$ /usr/bin/python3 "/home/sergey/Рабочий стол/main.py"
Terminal
application
20
1.37
from types import SimpleNamespace
json_data = {
"name": "Terminal",
"packageName": "application",
"order": 20,
"versionName": "1.37"
}
data = SimpleNamespace(**json_data)
print(data.name)
print(data.order)
#добавляем новое поле
data.new_field = "boo"
print(data)
Terminal
20
namespace(name='Terminal', packageName='application', order=20, versionName='1.37', new_field='boo')