Python:在循环中解析JSON

时间:2017-06-04 23:08:46

标签: python json if-statement yelp

我有一个函数可以从数据库中提取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."
  }
}

并且脚本在痛苦中死亡(实际上是我的痛苦):

enter image description here

对我而言,Python正在说:

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

哪个翻译意味着:"嘿伙计,你知道' business' JSON元素,响应中没有这样的元素,所以我不知道该怎么做,所以我就此止步。"

我如何构建类似的东西:继续做你的工作而if response_data['error']['code'] == 'LOCATION_NOT_FOUND':什么都不做?

5 个答案:

答案 0 :(得分:1)

if 'businesses' in response_data:
   for SQL_element in response_data['businesses']:
       …

答案 1 :(得分: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 ..."

答案 2 :(得分:0)

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

答案 3 :(得分:0)

在     response_data = response.json()

验证response_data是否有businesses密钥

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

答案 4 :(得分:0)

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

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

如果需要,您甚至可以返回类似状态的内容,例如

return True 
return False

有关return命令的更多信息,请参阅this question