Python - 有一种优雅的方法可以避免数十个try/except块从json对象中获取数据吗?

sen*_*nte 3 python json

我正在寻找编写函数的方法,get_profile(js)但没有所有丑陋的尝试/例外.

每个赋值都在try/except中,因为偶尔json字段不存在.我会很高兴有一个优雅的解决方案,None即使我设置了一些默认设置[],但是如果这样做会使整个代码更好,那么默认一切都是如此.

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
Run Code Online (Sandbox Code Playgroud)

psr*_*psr 8

  1. 使用词典get(key[, default])方法
  2. 代码生成此样板代码并为您节省更多麻烦.


Ale*_*x Q 8

使用字典get(key [,default])方法的链式调用替换每个try catch块.在链中最后一次调用之前获取的所有调用应该具有默认值{}(空字典),以便可以在有效对象上调用后面的调用,只有链中的最后一个调用应该具有默认值.你想要查找的关键.

有关dictionairies的信息,请参阅python文档http://docs.python.org/library/stdtypes.html#mapping-types-dict

例如:

d['links']     = js.get('entry', {}).get('gd$feedLink', [])
d['published'] = js.get('entry', {}).get('published',{}).get('$t', '')
Run Code Online (Sandbox Code Playgroud)