python如何利用动态属性处理JSON数据源

python如何利用动态属性处理JSON数据源" alt="python如何利用动态属性处理JSON数据源" src="//www.dapan.cc/wp-content/uploads/2022/11/1668480074-6871db378f02422.jpg">

利用动态属性处理JSON数据源

属性:在python中,数据的属性和处理数据的方法统称属性。

元编程:用元类进行编程,元类→类→对象,元类比类更抽象,生成类的类。

1、使用动态属性访问JSON类数据

第一版:利用json.load(fp)审查数据

fromurllib.requestimporturlopen
importwarnings
importos
importjson

URL='http://www.oreilly.com/pub/sc/osconfeed'
JSON='data/osconfeed.json'

defload():
ifnotos.path.exists(JSON):
msg='downloading{}to{}'.format(URL,JSON)
warnings.warn(msg)#如果需要下载就发出提醒。
withurlopen(URL)asremote,open(JSON,'wb')aslocal:#在with语句中使用两个上下文管理器分别用于读取和保存远程文件。
local.write(remote.read())
withopen(JSON)asfp:
returnjson.load(fp)#json.load函数解析JSON文件,返回python原生对象。

第二版:使用动态属性访问JSON类数据

第一版查阅深层数据的格式比较冗长,例如feed'Schedule'40,我们希望在读取属性上采用feed.Schedule.events[40].name这类方式来改进。并且第二版的类能递归,自动处理嵌套的映射和列表。

fromcollectionsimportabc

classFronenJSON():
def__init__(self,mapping):
self.__data=dict(mapping)#创建副本,同时确保处理的是字典。

def__getattr__(self,name):#仅当没有指定名称的属性才调用__getattr__方法。
ifhasattr(self,name):
returngetattr(self.__data,name)
else:
returnFronenJSON.build(self.__data[name])

@classmethod
def__build__(cls,obj):
ifisinstance(obj,abc.Mapping):#判断obj是否是映射。
returncls(obj)#创建FrozenJSON对象。
elifisinstance(obj,abc.MutableSequence):
return[cls.build(item)foriteminobj]#递归调用.build()方法,构建一个列表。
else:#既不是字典也不是列表,则返回元素本身。
returnobj

分析: FronenJSON类的关键是__getattr__方法。仅当无法使用常规的方式获取属性(即在实例、类或超类中找不到指定的属性),解释器才会调用特殊的__getattr__方法。

相关推荐:《python教程》

2、处理无效属性名

python中,由于关键字被保留,名称为关键字的属性是无效的。因此需要对第二版中的__init__进行改进:

def__init__(self,mapping):
self.__data={}
forkey,valueinmapping.items():
ifkeyword.iskeyword(key):
key+='_'#与python关键字重复的key在尾部加上下划线。
self.__data[key]=value

3、使用特殊方法__new__

fromcollectionsimportabc

classFronenJSON():
def__new__(cls,arg):#__new__是类方法,第一个参数是类本身cls。
ifisinstance(arg,abc.Mapping):
returnsuper().__new__(cls)#委托给超类object基类的__new__方法处理。
elifisinstance(arg,abc.MutableSequence):#余下方法与原先的build方法一致。
return[cls(item)foriteminarg]
else:
returnarg

def__init__(self,mapping):
self.__data={}
forkey,valueinmapping.items():
ifkeyword.iskeyword(key):
key+='_'
self.__data[key]=value

def__getattr__(self,name):
ifhasattr(self,name):
returngetattr(self.__data,name)
else:
returnFronenJSON(self.__data[name])