2017-06-04 41 views
0

我有一個函數,可以從數據庫中拾取Country,City,Latitude,Longitude,並在特定業務上搜索Yelp API。Python:在循環中解析JSON

,一切工作正常:

def get_movietheaters_for(country, city, latitude, longitude): 
    connection2 = pyodbc.connect('DRIVER={SQL Server};'      
           'SERVER=ASPIRES3;'       
           'DATABASE=worldcitiespop;'     
           'UID=sqlninja;'        
           'PWD=sqlninja')        
    cursor2 = connection2.cursor()           
    # Call Yelp API to pull business data         
    # (Yelp v3 API: https://nz.yelp.com/developers/documentation/v3)   
    url = 'https://api.yelp.com/v3/businesses/search'      
    params = {'cc': country,             
       'location': city,            
       'cll': "%s,%s" % (latitude, longitude),      
       'categories': args.category,         
       'limit': args.limit}           
    response = requests.get(url = url, headers = headers, params=params)  
    # if response.status_code == 200:          
    response_data = response.json()           

    sqlStatement = "INSERT INTO VistaYelp (ID, Name, City, Zip_code, Country, State, Address1, Address2, Address3, Latitude, Longitude, Phone, Yelp_URL, Review_Count, Rating) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" # Query 
    # Here we go to store JSON elements for SQL 


    for SQL_element in response_data['businesses']: 
     SQL_ID = SQL_element['id']              
     SQL_Name = SQL_element['name']             
     SQL_City = SQL_element['location']['city']          
     SQL_Zip_code = SQL_element['location']['zip_code']        
     SQL_Country = SQL_element['location']['country']         
     SQL_State = SQL_element['location']['state']          
     SQL_Address1 = SQL_element['location']['address1']        
     SQL_Address2 = SQL_element['location']['address2']        
     SQL_Address3 = SQL_element['location']['address3']        
     SQL_Latitude = SQL_element['coordinates']['latitude']       
     SQL_Longitude = SQL_element['coordinates']['longitude']       
     SQL_Phone = SQL_element['phone']             
     SQL_YelpURL = SQL_element['url']             
     SQL_Review = SQL_element['review_count']           
     SQL_Rating = SQL_element['rating']            

     if args.do == 'show': 
      print (SQL_ID,SQL_Name,SQL_City,SQL_Zip_code,SQL_Country,SQL_State, 
       SQL_Address1,SQL_Address2,SQL_Address3,SQL_Latitude,SQL_Longitude,SQL_Phone) 
     elif args.do == 'save':  
      cursor2.execute(sqlStatement, SQL_ID,SQL_Name,SQL_City,SQL_Zip_code,SQL_Country,SQL_State,SQL_Address1,SQL_Address2,SQL_Address3,SQL_Latitude,SQL_Longitude,SQL_Phone,SQL_YelpURL,SQL_Review,SQL_Rating) 
      connection2.commit() 

    if args.do == 'show': 
     print ('\nTotal Cinemas found: ' , len(response_data['businesses']),' for Latitude and Longitude ', latitude, longitude) 
    elif args.do == 'save': 
     print ('\nTotal Cinemas found and saved in database: ' , len(response_data['businesses']),' for', latitude, longitude) 

問題開始當腳本搜索不存在或不是在Yelp的數據庫,那麼JSON調用返回我的一個小鎮:

{ 
    "error": { 
    "code": "LOCATION_NOT_FOUND", 
    "description": "Could not execute search, try specifying a more exact location." 
    } 
} 

和腳本極度痛苦(我的痛苦其實)死亡:

enter image description here

而且是有意義的我,Python是說:

for SQL_element in response_data['businesses']: 
KeyError: 'businesses' 

這翻譯的意思是:「嘿,夥計,你知道‘企業’JSON元素,還有在響應沒有這樣的元素,所以不知道該怎麼做,所以我停下來。「

我該如何構建這樣的東西:繼續做你的工作,if response_data['error']['code'] == 'LOCATION_NOT_FOUND':什麼都不做?

回答

1
if 'businesses' in response_data: 
    for SQL_element in response_data['businesses']: 
     … 
0
response_data = response.json() 

if response_data['error']['code'] == 'LOCATION_NOT_FOUND': 
    # if nothing found, print a message and terminate the function 
    print('No cinemas found.') 
    return 

# otherwise keep on going 
sqlStatement = "INSERT INTO ..." 
+0

這會給你一個關鍵的錯誤,如果沒有錯誤 – gipsy

+0

是的,但這是OP寫的測試條件的確切代碼,所以我用它。 –

0
response_data = response.json() 
if response_data.get('error'): 
    return # Do nothing and return 
0

後 RESPONSE_DATA = response.json()

驗證是否response_data擁有businesses關鍵

If `businesses` in response_data.keys(): 
    # Do the code 
0

你應該嘗試捕獲錯誤並中止進一步執行該功能。

if "error" in response_data: 
    return #Function will stop on a return call 

如果您願意,甚至可以返回類似狀態的內容,例如,

return True 
return False 

有關return命令的更多信息,請參閱this question