簡體   English   中英

Python:循環解析JSON

[英]Python: parse JSON in loop

我有一個功能,可以從數據庫中提取Country,City,Latitude,Longitude ,並在Yelp API上搜索特定業務。

一切正常:

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."
  }
}

劇本死於可怕的痛苦(實際上是我的痛苦):

在此處輸入圖片說明

對我來說,Python在說:

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

翻譯的意思是:“伙計,您知道'businesses'JSON元素,響應中沒有這樣的元素,所以我不知道該怎么做,所以我就在這里停止。”

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

if 'businesses' in response_data:
   for SQL_element in response_data['businesses']:
       …
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 ..."
response_data = response.json()
if response_data.get('error'):
  return  # Do nothing and return

在response_data = response.json()之后

驗證response_data是否具有businesses密鑰

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

您可能應該嘗試捕獲該錯誤並中止該函數的進一步執行。

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

您甚至可以根據需要返回類似狀態的信息,例如

return True 
return False

有關return命令的更多信息,請參見此問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM