If and else statement in Google Places API script in Python
Question: I am attempting to write a script that will loop through list items and query
the google places api.

The problem is that some of the queries will return no results, while other
queries will.

The query results are gathered into lists. For every query that returns no
results I would like to insert 'no results' string into list.

This is the script I have so far (API Key is fake):

    
    
    companies = ['company A', 'company B', 'company C']    
    
    #create list items to store API search results
    google_name = []
    place_id = []
    formatted_address = []
    
    
    
    #function to find company id and address from company names
    def places_api_id():
        api_key = 'AIzaSyAKCp1kN0cHvO7t_NlqMagergrghhehtsrht'
        url = 'https://maps.googleapis.com/maps/api/place/textsearch/json'
        #replace spaces within list items with %20
        company_replaced = company.replace(' ', '%20')
        final_url = url + '?query=' + company_replaced +'&key=' + api_key
        json_obj = urllib2.urlopen(final_url)
        data = json.loads(json_obj)
    
        #if no results, insert 'no results'
        if data['status'] == 'ZERO RESULTS':
            google_name.append('no results')
            place_id.append('no results')
            formatted_address('no results')
    
        #otherwise, insert the result into list
        else:
            for item in data['results']:
                google_name.append(item['name'])
                place_id.append(item['place_id'])
                formatted_address.append(item['formatted_address'])
    
    #run the script
    for company in companies:
        places_api_id()
    

Unfortunately when I run the script python produces the following error:

    
    
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-159-eadf5f84e27f> in <module>()
          1 for company in companies:
    ----> 2     places_api_id()
          3 
    
    <ipython-input-153-f0e25b871a0e> in places_api_id()
          6         final_url = url + '?query=' + company_replaced +'&key=' +     api_key
          7         json_obj = urllib2.urlopen(final_url)
    ----> 8         data = json.loads(json_obj)
      9         if data['status'] == 'ZERO RESULTS':
     10                 google_name.append('no results')
    
    /usr/lib/python2.7/json/__init__.pyc in loads(s, encoding, cls, object_hook,     parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
        336             parse_int is None and parse_float is None and
        337             parse_constant is None and object_pairs_hook is None and not     kw):
    --> 338         return _default_decoder.decode(s)
        339     if cls is None:
        340         cls = JSONDecoder
    
    /usr/lib/python2.7/json/decoder.pyc in decode(self, s, _w)
        364 
        365         """
    --> 366         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
        367         end = _w(s, end).end()
        368         if end != len(s):
    
    `TypeError: expected string or buffer
    

I would really appreciate your help and advice on how to get this script
working, I've been staring at it for hours.

Thank you Kamil

UPDATE

I am now loooping the following list through the script:

    
    
    companies = ['MARINE AND GENERAL MUTUAL LIFE ASSURANCE SOCIETY',
     'KENTSTONE PROPERTIES LIMITED',
     'ASHFORD CATTLE MARKET COMPANY LIMITED(THE)',
     'ORIENTAL GAS COMPANY, LIMITED(THE)',
     'BRITISH INDIA STEAM NAVIGATION COMPANY LIMITED',
     'N & C BUILDING PRODUCTS LIMITED',
     'UNION MARINE AND GENERAL INSURANCE COMPANY LIMITED,(THE)',
     '00000258 LIMITED',
     'METHODIST NEWSPAPER COMPANY LIMITED',
     'LONDON AND SUBURBAN LAND AND BUILDING COMPANY LIMITED(THE)']
    

after I run the script this is what Google Places API returns in the google
name list:

    
    
    [u'The Ashford Cattle Market Co Ltd',
     u'Orient Express Hotels',
     u'British-India Steam-Navigation Co Ltd',
     u'N-Of-One, Inc.',
     u'In-N-Out Burger',
     u'In-N-Out Burger Distribution Center',
     u"Wet 'n Wild Orlando",
     u'In-N-Out Burger',
     u'Alt-N Technologies (MDaemon)',
     u'Model N Inc',
     u"Pies 'n' Thighs",
     u"Bethany Women's Center",
     u"Jim 'N Nick's Bar-B-Q",
     u"Steak 'n Shake",
     u'New Orleans Ernest N. Morial Convention Center',
     u"Jim 'N Nick's Bar-B-Q",
     u"Jim 'N Nick's Bar-B-Q",
     u"Jim 'N Nick's Bar-B-Q",
     u'Theatre N at Nemours',
     u'Model N',
     u"Jim 'N Nick's Bar-B-Q",
     u'Memphis Rock n Soul Museum',
     u"Eat'n Park - Squirrel Hill",
     u'Travelers',
     u'American General Life Insurance Co',
     u'258 Ltd Rd',
     u'The Limited',
     u'258, New IPCL Rd',
     u'London Metropolitan Archives',
     u'Hampstead Garden Suburb Trust Ltd']
    

Majority of the company names returned by Google are not even on the companies
list and also there are many more of them. I am really confused now.


Answer: The error is not at the `if`-line, but before. `json_obj` is a file-like
object, not a string, therefore you have to use `load`:

    
    
    data = json.load(json_obj)
    

PS: if the status is not what you expect, you can just test if
`data['results']` is empty or not:

    
    
    import urllib2
    from collections import namedtuple
    
    API_KEY = 'AIzaSyAKCp1kN0cHvO7t_NlqMagergrghhehtsrht'
    URL = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query={q}&key={k}'
    Place = namedtuple("Place", "google_name,place_id,formatted_address")
    
    #function to find company id and address from company names
    def places_api_id(company):
        places = []
        url = URL.format(q=urllib2.quote(company), k=API_KEY)
        json_obj = urllib2.urlopen(url)
        data = json.loads(json_obj)
    
        if not data['results']:
            places.append(Place("no results", "no results", "no results"))
        else:
            for item in data['results']:
                places.append(Place(item['name'], item['place_id'], item['formatted_address']))
        return places
    
    companies = ['company A', 'company B', 'company C']    
    places = []
    for company in companies:
        places.extend(places_api_id(company))
    

