2015-05-05 85 views
2

這裏是JSON數據,我有:解析JSON使用Python和if語句

{ 
    "response": { 
    "status": { 
     "version": "4.2", 
     "code": 0, 
     "message": "Success" 
    }, 
    "artists": [ 
     { 
     "name": "Taylor Swift", 
     "foreign_ids": [ 
      { 
      "catalog": "facebook", 
      "foreign_id": "facebook:artist:19614945368" 
      } 
     ], 
     "hotttnesss": 0.99956, 
     "id": "ARS54I31187FB46721" 
     }, 
     { 
     "name": "Ed Sheeran", 
     "foreign_ids": [ 
      { 
      "catalog": "facebook", 
      "foreign_id": "facebook:artist:9189674485" 
      } 
     ], 
     "hotttnesss": 0.994265, 
     "id": "ARSDWSZ122ECCB706A" 
     }, 
     { 
     "name": "Calvin Harris", 
     "foreign_ids": [ 
      { 
      "catalog": "facebook", 
      "foreign_id": "facebook:artist:19366141168" 
      } 
     ], 
     "hotttnesss": 0.990559, 
     "id": "ARJRB241187FB556A3" 
     }, 
     { 
     "name": "Sam Smith", 
     "foreign_ids": [ 
      { 
      "catalog": "facebook", 
      "foreign_id": "facebook:artist:313595788739120" 
      } 
     ], 
     "hotttnesss": 0.988203, 
     "id": "ARUZM8A11C8A41519C" 
     }, 
     { 
     "name": "Maroon 5", 
     "foreign_ids": [ 
      { 
      "catalog": "facebook", 
      "foreign_id": "facebook:artist:5330548481" 
      } 
     ], 
     "hotttnesss": 0.984929, 
     "id": "ARF5M7Q1187FB501E8" 
     }, 
     { 
     "name": "Sia", 
     "foreign_ids": [ 
      { 
      "catalog": "facebook", 
      "foreign_id": "facebook:artist:10959868407" 
      } 
     ], 
     "hotttnesss": 0.983516, 
     "id": "AR6ENUY1187B994158" 
     }, 
     { 
     "name": "David Guetta", 
     "foreign_ids": [ 
      { 
      "catalog": "facebook", 
      "foreign_id": "facebook:artist:7619396355" 
      } 
     ], 
     "hotttnesss": 0.982656, 
     "id": "ARH2QI91187FB3788D" 
     }, 
     { 
     "name": "Ellie Goulding", 
     "foreign_ids": [ 
      { 
      "catalog": "facebook", 
      "foreign_id": "facebook:artist:135027136641" 
      } 
     ], 
     "hotttnesss": 0.981786, 
     "id": "ARKTTJV12592CDA07F" 
     }, 
     { 
     "name": "Wiz Khalifa", 
     "foreign_ids": [ 
      { 
      "catalog": "facebook", 
      "foreign_id": "facebook:artist:12138756141" 
      } 
     ], 
     "hotttnesss": 0.978492, 
     "id": "ARN0GFV1187FB508CC" 
     }, 
     { 
     "name": "Ariana Grande", 
     "hotttnesss": 0.978074, 
     "id": "AROHQCR13244CF7152" 
     } 
    ] 
    } 
} 

我試圖解析「目錄」和「foreign_id」。這裏是我的代碼:

for item in data['response']['artists']: 
    for row in item['foreign_ids']: 
     print row['catalog'], row['foreign_id'] 

的結果是:

facebook facebook:artist:19614945368 
facebook facebook:artist:9189674485 
facebook facebook:artist:19366141168 
facebook facebook:artist:313595788739120 
facebook facebook:artist:5330548481 
facebook facebook:artist:10959868407 
facebook facebook:artist:7619396355 
facebook facebook:artist:135027136641 
facebook facebook:artist:12138756141 

KeyError 
Traceback (most recent call last) 
<ipython-input-224-cbc34d6d831e> in <module>() 
     1 for item in data['response']['artists']: 
----> 2  for row in item['foreign_ids']: 
     3   print row['catalog'], row['foreign_id'] 

KeyError: 'foreign_ids' 

我想我知道爲什麼;最後一個數據行沒有「foreign_ids」。如何包含if語句以幫助我避免此錯誤?例如,當沒有名爲「foreign_ids」的數組值時,代碼輸出「無」。

回答

2

在嘗試迭代它之前,您必須檢查該列是否存在。這種方法被稱爲「看你跳躍之前」。這裏我們使用的是get,因爲默認情況下它將返回None,而不會提高KeyError

for item in data['response']['artists']: 
    if item.get('foreign_ids'): 
     for row in item['foreign_ids']: 
      print row['catalog'], row['foreign_id'] 

另外,還可以採用通過get它提供一個空的列表,而不是遍歷一個默認值。

for item in data['response']['artists']: 
    for row in item.get('foreign_ids', []): 
     print row['catalog'], row['foreign_id'] 

在這兩種情況下,你必須檢查,看看是否存在的關鍵。你所擁有的代碼假設它總是存在的,這絕對不是這種情況。

+0

謝謝大家好的建議! – kevin

0
if 'foreign_ids' not in item: 
    continue 
for row in item['foreign_ids']: 
.... 
+0

我會以另一種方式寫入它(例如,'if'foreign_ids'in item:'),但這足夠了。 – Makoto

+0

我更喜歡continue方法,因爲它可以緩解大量的縮進:)。給每個人自己。 –

1

你可以檢查,看看是否關鍵是JSON對象的那部分做:

if 'somekey' in somPartOfTheJson: 
    jsonObj = json.loads(jsonStr) 

    for item in jsonObj['response']['artists']: 
     if 'foreign_ids' in item: 
      for row in item['foreign_ids']: 
       if 'catalog' in row and 'foreign_id' in row: 
        print row['catalog'], row['foreign_id'] 
+0

感謝您的建議!這工作。 – kevin

1

代替if聲明(這是完全合法的),你可以使用try/except塊:

for item in data['response']['artists']: 
    try:  
     for row in item['foreign_ids']: 
      print row['catalog'], row['foreign_id'] 
    except KeyError as Ex: 
     print "{} not found in {}".format(Ex,item) 

這給:

... 
facebook facebook:artist:7619396355 
facebook facebook:artist:135027136641 
facebook facebook:artist:12138756141 
'foreign_ids' not found in {'id': 'AROHQCR13244CF7152', 'name': 'Ariana Grande', 'hotttnesss': 0.978074} 

這IMO是因爲它清潔一明確認識到問題並採取行動。而不是打印,你可以做一個替代動作,如log

+0

感謝您的建議!這工作。 – kevin