Here is my json response
{u’kind’: u’bigquery#queryResponse’, u’rows’: [{u’f’: [{u’v’: u’1′}, {u’v’: u’1607′}, {u’v’: u’coriolanus’}]}, {u’f’: [{u’v’: u’1′}, {u’v’: u’1596′}, {u’v’: u’kingjohn’}]}, {u’f’: [{u’v’: u’1′}, {u’v’: u’1599′}, {u’v’: u’kinghenryv’}]}, {u’f’: [{u’v’: u’1′}, {u’v’: u’1600′}, {u’v’: u’merrywivesofwindsor’}]}, {u’f’: [{u’v’: u’1′}, {u’v’: u’1602′}, {u’v’: u’troilusandcressida’}]}, {u’f’: [{u’v’: u’1′}, {u’v’: u’1592′}, {u’v’: u’comedyoferrors’}]}, {u’f’: [{u’v’: u’2′}, {u’v’: u’1590′}, {u’v’: u’3kinghenryvi’}]}, {u’f’: [{u’v’: u’2′}, {u’v’: u’1612′}, {u’v’: u’kinghenryviii’}]}, {u’f’: [{u’v’: u’2′}, {u’v’: u’1598′}, {u’v’: u’2kinghenryiv’}]}], u’jobReference’: {u’projectId’: u’1039435439624′, u’jobId’: u’job_ffb30cfb23674f88aa5cb497e358ec05′}, u’jobComplete’: True, u’totalRows’: u’9′, u’schema’: {u’fields’: [{u’type’: u’INTEGER’, u’name’: u’sum_for_the’, u’mode’: u’NULLABLE’}, {u’type’: u’INTEGER’, u’name’: u’corpus_date’, u’mode’: u’NULLABLE’}, {u’type’: u’STRING’, u’name’: u’f0_’, u’mode’: u’NULLABLE’}]}}
I loop through this using the below python code
resp = []
for row in listReply['rows']:
for key,dict_list in row.iteritems():
count = dict_list[0]
year = dict_list[1]
corpus = dict_list[2]
resp.append({'count': count['v'],'year':year['v'],'corpus':corpus['v']})
How to check if this listReply['rows'] exists or not as in case of a json response such as below
{u’totalRows’: u’0′, u’kind’: u’bigquery#queryResponse’, u’jobComplete’: True, u’jobReference’: {u’projectId’: u’1039435439624′, u’jobId’: u’job_8efc645852c34515bcff4ab3969772fd’}, u’schema’: {u’fields’: [{u’type’: u’INTEGER’, u’name’: u’sum_for_the’, u’mode’: u’NULLABLE’}, {u’type’: u’INTEGER’, u’name’: u’corpus_date’, u’mode’: u’NULLABLE’}, {u’type’: u’STRING’, u’name’: u’f0_’, u’mode’: u’NULLABLE’}]}}
If listReply has a key “rows”, this will iterate over the corresponding value. If the key doesn’t exist, the default is returned, which should be an empty list in this case so
forwill not complain since it is iterable.Another way is to test for the key before entering the for loop.