2012-11-27 73 views
2

這裏是我的JSON響應檢查是否JSON響應行存在與否和Python

{u'kind ':u'bigquery#queryResponse' u'rows「:[{u'f「: [{UV:U'1 '},{UV:u'1607'},{UV:u'coriolanus '}]},{u'f':[{UV ':U'1'},{UV:u'1596 '},{UV:u'kingjohn'}]},{u'f「:[{UV:U'1 '},{UV:u'1599'},{UV:u'kinghenryv '}]},{u'f':[{UV:U'1「},{藍ν:u'1600 '},{UV:u'merrywivesofwindsor'}]},{u'f ':[{UV:U'1'},{UV我'1602'},{UV:u'troilusandcressida '}]},{u'f':[{UV:U'1 '},{UV:u'1592'}, {UV:u'comedyoferrors '}]},{u'f':[{UV:U'2 '},{UV:u'1590'},{UV :u'3kinghenryvi '}]},{u'f':[{UV:U'2 '},{UV:u'1612'},{UV:u'kinghenryviii' }]},{u'f ':[{UV:U'2'},{UV:u'1598 '},{UV:u'2kinghenryiv'}]}], u'jobRefe天信 ':{u'projectId':u'1039435439624 'u'jobId':u'job_ffb30cfb23674f88aa5cb497e358ec05 '},u'jobComplete':真,u'totalRows ':u'9' u'schema ':{在'字段:[{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'}] }}

和使用該環路通過下面

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']}) 

的Python代碼如何檢查是否此listReply['rows']存在與否,如如下面JSON

的響應的情況下

{u'totalRows ':u'0' u'kind ':u'bigquery#queryResponse' u'jobComplete ':真,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'type ':u'INTEGER',u'name ':u'corpus_date',u'mode ':u'NULLABLE'},{u'type ':u'STRING',U'名 ':u'f0_' u'mode ':u'NULLABLE'}]}}

回答

4
for row in listReply.get('rows', []): 

如果listReply有一個關鍵的「行」,這將遍歷相應的值。如果該鍵不存在,則默認返回,這應該是在這種情況下,一個空的列表是for不會抱怨,因爲它是可迭代。

另一種方式是在進入for循環,用於測試的關鍵。

if 'rows' in listReply: 
    for row in listReply['rows']: 
     ... 
+0

但第二種方法什麼是進入for循環之前的行 – iJade

+0

@jade,抱歉,這是一個錯字。這就是爲什麼我喜歡前者 - 減少犯錯誤的機會:) –

3

您可以使用

if key in aDict: 
    # Operations 

爲了測試在Python詞典中的條目的存在。如果這將是一個空列表,你也可以這樣做:

if key in aDict and aDict[key]: 
    # Operations 

因爲評價爲從左到右,如果鑰匙丟失了第二次檢查將不會被執行,但如果它存在,空,第二次檢查將跳過操作。

+0

平均,如果行和listReply和listReply [ '行'] – iJade

+0

@jade - 是的,'F '行' 和listReply'。此外,'listReply.get( '行',[])'作爲替代。 –

0

要檢查的關鍵存在於dict使用in關鍵字。

>>> d = {} 
>>> 1 in d 
16: False 
>>> d[1] = 1 
>>> 1 in d 
17: True 
>>> d 
18: {1: 1} 

必須使用你的例子

>>> d = {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'}]}} 
>>> 'rows' in d 
19: False