I have developed a small library and am interested in making it easier on users to retrieve data from the JSON lists/dictionaries that are returned. I have created functions that handle the calls using requests. Now suppose I call this function and pass in a few parameters:
precip = precipitation_obs(stid='kfnl', start='201504261800', end='201504271200', units='precip|in')
This will return the following 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'}}
Now, I want the user to be able to just drill down through the dictionary, but STATION is a list and requires me to do the following:
output = precip['STATION'][0]['OBSERVATIONS']['ob_start_time_1']
print(output)
# returns 2015-04-26T18:55:00Z
where I have to include the [0] to avoid:
TypeError: list indices must be integers, not str
Is there anyway around this? 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. Should I use the simpleJSON module to help here? Any tips on making this a bit easier would be great, thanks!
simplejsonis not going to help here, because it just parses JSON to the corresponding Python structure.[0]step, because if there are 3 stations, you need to be able to access #0, #1, and #2. You could change that list into a dict keyed by, say, each station's'STID'value (so it would beprecip['STATION']['KFNL']['OBSERVATIONS']['ob_start_time_1']), but you can't get rid of it.