每个赋值都在try / except中,因为偶尔Json字段不存在.我很高兴有一个优雅的解决方案,默认一切都为无,即使我将一些默认设置为[]等,如果这样做会使整个代码更好.
def get_profile(Js): """ given a Json object,return a dict of a subset of the data. what are some cleaner/terser ways to implement this? There will be many other get_foo(Js),get_bar(Js) functions which need to do the same general type of thing. """ d = {} try: d['links'] = Js['entry']['gd$Feedlink'] except: d['links'] = [] try: d['statisitcs'] = Js['entry']['yt$statistics'] except: d['statistics'] = {} try: d['published'] = Js['entry']['published']['$t'] except: d['published'] = '' try: d['updated'] = Js['entry']['updated']['$t'] except: d['updated'] = '' try: d['age'] = Js['entry']['yt$age']['$t'] except: d['age'] = 0 try: d['name'] = Js['entry']['author'][0]['name']['$t'] except: d['name'] = '' return d解决方法 试试像……
import timedef get_profile(Js): def cas(prev,el): if hasattr(prev,"get") and prev: return prev.get(el,prev) return prev def getget(default,*elements): return reduce(cas,elements[1:],Js.get(elements[0],default)) d = {} d['links'] = getget([],'entry','gd$Feedlink') d['statistics'] = getget({},'yt$statistics') d['published'] = getget('','published','$t') d['updated'] = getget('','updated','$t') d['age'] = getget(0,'yt$age','$t') d['name'] = getget('','author','name' '$t') return dprint get_profile({ 'entry':{ 'gd$Feedlink':range(4),'yt$statistics':{'foo':1,'bar':2},'published':{ "$t":time.strftime("%x %X"),},'updated':{ "$t":time.strftime("%x %X"),'yt$age':{ "$t":"infinity years",'author':{0:{'name':{'$t':"I am a cow"}}},}})
对我来说,假设你有一个带有0的键而不是列表的字典,这是一种信念的飞跃,但是……你明白了.
总结以上是内存溢出为你收集整理的Python – 有一种优雅的方法可以避免数十个try / except块从json对象中获取数据吗?全部内容,希望文章能够帮你解决Python – 有一种优雅的方法可以避免数十个try / except块从json对象中获取数据吗?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)