Python:在循环中解析JSON [英] Python: parse JSON in loop

查看:197
本文介绍了Python:在循环中解析JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能,从数据库中提取国家,城市,纬度,经度,并在Yelp API上搜索特定业务。

I have a function that pick-ups Country,City,Latitude,Longitude from a database and search on Yelp API for particular business.

一切正常:

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调用会返回我:

Problem start when the script search for a town that doesn't exists or is not in the Yelp database, so JSON call returns me:

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

脚本死于痛苦(我的痛苦其实):

and the script dies in terrible pain (my pain actually):

这对我来说很有意义,Python说:

And it make sense to me, Python is saying:

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

翻译的意思是:嘿伙计,你知道'企业'的JSON元素,在这里没有这样的元素响应,所以我不知道该怎么做,所以我就此止步。

Which translated means:"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."

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

How can I structure something like: keep doing your job and if response_data['error']['code'] == 'LOCATION_NOT_FOUND': do nothing?

推荐答案

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

这篇关于Python:在循环中解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆