2

I am trying this code and getting the error in lines starting with lat, lng and location. Can anyone please help?

import urllib.parse
import urllib.request
import json
while True:
    address = input('Enter location: ')
    if len(address) < 1 : break 
    serviceurl = 'http://python-data.dr-chuck.net/geojson'
    url = serviceurl + '?' + urllib.parse.urlencode({'sensor':'false', 'address':  address})
   response = urllib.request.urlopen(url)
data = response.readall().decode('utf-8')
js = json.loads(str(data))
if 'status' not in js or js['status'] != 'OK':
    print ('==== Failure To Retrieve ====')
    print (data)
    continue
    print (json.dumps(js, indent=4))

    lat = js["results"][0]["geometry"]["location"]["lat"]
    lng = js["results"][0]["geometry"]["location"]["lng"]
    print('lat',lat) #,('lng'),lng
    location = js['results'[0]]['formatted_address']
    print(location)

Thanks, Arun

Arun.K
  • 103
  • 2
  • 4
  • 21
  • at least one of the fields is empty – Pynchia Dec 23 '15 at 23:58
  • If you print the entire `js` object you'll see what fields it has. – Turn Dec 24 '15 at 00:01
  • Aside from your question... don't do this: `if 'status' or 'OK' in js == False`. Because: 1. `'status' or 'OK' in js` always evaluates to `'status'`, and 2. you don't ever want to compare to `True` or `False`. Either do `if something` or `if not something`. That will save you from some unexpected problems. BTW `'status' or 'OK' in js == False` also evaluates to `'status'`, so your `if` is always true ;) – zvone Dec 24 '15 at 00:06

1 Answers1

5

The error, NoneType object is not subscriptable means that you tried to do:

None[something]

If it happens in this line: js["results"][0]["geometry"]["location"]["lat"], that means js["results"][0]["geometry"]["location"]["lat"] does not exist, i.e. something along that path evaluated to None.

For example, if js is None, it will fail trying to evaluate None["results"].

Or, if js["results"][0] is None, it will fail trying to do None["geometry"] etc.

BTW, it is very likely that js is None, because you do have this:

except: js = None
zvone
  • 18,045
  • 3
  • 49
  • 77
  • Ok. Thanks for all the comments. I modified the code edited the question and i am getting this error - `raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 400: Bad Request` – Arun.K Dec 24 '15 at 00:38
  • That is the response you get from server. It does not like the request. Maybe you are missing some data or you missspelled something or the server expects a session cookie or who knows what... – zvone Dec 24 '15 at 00:46