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 致电 returns 我:

{
  "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'

翻译的意思是:"Hey dude, you know 'businesses' JSON element, there is no such element in the response, so I don't know what to do, so I stop here."

我怎样才能构建这样的结构:继续做你的工作,if response_data['error']['code'] == 'LOCATION_NOT_FOUND':什么都不做?

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 'businesses' in response_data:
   for SQL_element in response_data['businesses']:
       …

您可能应该尝试捕获错误并中止函数的进一步执行。

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

如果需要,您甚至可以 return 状态之类的东西,例如

return True 
return False

有关 return 命令的详细信息,请参阅 this question