JSON list/dictionary 从 API 解析

JSON list/dictionary parsing from API

我开发了一个小型库,并且有兴趣让用户更轻松地从 JSON lists/dictionaries 检索 return 编辑的数据。我创建了使用 requests 处理调用的函数。现在假设我调用这个函数并传入几个参数:

precip = precipitation_obs(stid='kfnl', start='201504261800', end='201504271200', units='precip|in')

这将 return 以下 JSON:

{ 'STATION': [ { 'ELEVATION': '5016',
                 'ID': '192',
                 'LATITUDE': '40.45',
                 'LONGITUDE': '-105.01667',
                 'MNET_ID': '1',
                 'NAME': 'Fort Collins/Loveland, Fort Collins-Loveland '
                         'Municipal Airport',
                 'OBSERVATIONS': { 'count_1': 6,
                                   'ob_end_time_1': '2015-04-27T00:55:00Z',
                                   'ob_start_time_1': '2015-04-26T18:55:00Z',
                                   'total_precip_value_1': 0.13,
                                   'vids case4': ['39', '51', '40', '52']},
                 'STATE': 'CO',
                 'STATUS': 'ACTIVE',
                 'STID': 'KFNL',
                 'TIMEZONE': 'US/Mountain'}],
  'SUMMARY': { 'METADATA_RESPONSE_TIME': '5.22613525391 ms',
               'NUMBER_OF_OBJECTS': 1,
               'RESPONSE_CODE': 1,
               'RESPONSE_MESSAGE': 'OK',
               'TOTAL_TIME': '57.6429367065 ms'}}    

现在,我希望用户能够通过字典向下钻取,但 STATION 是一个列表,需要我执行以下操作:

output =  precip['STATION'][0]['OBSERVATIONS']['ob_start_time_1'] 
print(output)
# returns 2015-04-26T18:55:00Z

我必须在其中包含 [0] 以避免:

TypeError: list indices must be integers, not str

这附近有没有?可以说,在其中添加 [0] 真的很重要。或者甚至每次都必须指定 ['STATION'] 有点麻烦。我应该使用 simpleJSON 模块来提供帮助吗?任何让这更容易的提示都会很棒,谢谢!

Adding that [0] in there really jacks things up so to say. Or even having to specify ['STATION'] every time is a bit of a nuisance.

所以只需将 precip['STATION'][0] 存储在一个变量中:

>>> precip0 = precip['STATION'][0]

现在,您可以重复使用它了:

>>> precip0['OBSERVATIONS']['ob_start_time_1']
2015-04-26T18:55:00Z

如果您知道 API 总是去往 return 恰好一个站,并且除了该站的数据之外您永远不需要任何其他东西,您可以将其放入你的包装函数:

def precipitation_obs(stid, start, end, units):
    # your existing code, which assigns something to result
    return result['STATION'][0]

如果您担心 "efficiency" 这里的问题,请不要担心。首先,这并没有复制任何东西,它只是对已经存在的同一个对象进行另一个引用——它花费的时间不到一微秒,并且浪费了大约 8 个字节。事实上,它 节省 你的内存,因为如果你不存储整个字典,只存储子字典, Python 可以垃圾收集结构的其余部分。而且,更重要的是,在 (1) 您的代码正常工作并且 (2) 您知道它是一个瓶颈之前,这​​种微优化一开始就不值得担心。


Should I use the simpleJSON module to help here?

为什么您认为这会有帮助?作为 its readme says:

simplejson is the externally maintained development version of the json library included with Python 2.6 and Python 3.0, but maintains backwards compatibility with Python 2.5.

换句话说,它要么是您已经在 stdlib 中获得的相同代码,要么是该代码的旧版本。

有时 不同的 库,例如 ijson,可以提供帮助——例如,如果 JSON 结构太大以至于您无法解析整个事情都存入内存,或者太复杂以至于更容易用 SAX 风格颠倒来描述你想要的东西。但这与这里无关。