0

The program will prompt for a location, contact a web service and retrieve JSON for the web service and parse that data, and retrieve the first place_id from the JSON. A place ID is a textual identifier that uniquely identifies a place as within Google Maps.

API End Points

To complete this assignment, you should use this API endpoint that has a static subset of the Google Data:

http://py4e-data.dr-chuck.net/json? This API uses the same parameter (address) as the Google API. This API also has no rate limit so you can test as often as you like. If you visit the URL with no parameters, you get "No address..." response.

I have worked on this assignment, but the codes are not running. I am JSONDecodeError whenever I run the program.

import urllib.request, urllib.parse, urllib.error
import json
adr= 'http://py4e-data.dr-chuck.net/json?'
while True:
    loca= input('Enter Location: ')
    if len(loca)<1:break

    url=adr + urllib.parse.urlencode({"address": loca})
    print('Retrieving', url)
    fha=urllib.request.urlopen(url)
    data=fha.read().decode()
    print('Retrieved', len(data))

    jsdata=json.loads(str(data))
    placeid= jsdata['results'][0]['place_id']
    print('The Place ID is: ', placeid)
1
  • Please share the entire error message. Commented Jan 12, 2020 at 22:37

7 Answers 7

4
import urllib.error, urllib.request, urllib.parse
import json

target = 'http://py4e-data.dr-chuck.net/json?' 
local = input('Enter location: ')
url = target + urllib.parse.urlencode({'address': local, 'key' : 42})

print('Retriving', url)
data = urllib.request.urlopen(url).read()
print('Retrived', len(data), 'characters')
js = json.loads(data)
print(json.dumps(js, indent = 4)) 
print('Place id', js['results'][0]['place_id'])
Sign up to request clarification or add additional context in comments.

1 Comment

Your code is working fine but it's better always to add try and except block: try: js = json.loads(html) except: js = None print(json.dumps(js, indent = 4))
2

It seems that the error is that this expects an extra parameter (Key)

Missing/incorrect key = parameter (it is an easy number to guess) ...

Edit: Check the documentation https://www.py4e.com/code3/geodata/README.txt

Example 1: http://py4e-data.dr-chuck.net/json?key=42&address=Monash+University

Example 2: http://py4e-data.dr-chuck.net/json?key=42&address=Kokshetau+Institute+of+Economics+and+Management

1 Comment

Thank you very much. Your answer really helped me.
2

This is the most updated code for the query

import json,ssl
import urllib.request,urllib.parse, urllib.error



# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE



#Stroring the given parameters
api_key = 42
serviceurl = "http://py4e-data.dr-chuck.net/json?"
# sample_address = "South Federal University"
data_address = "South Federal University"
address_wanted = data_address

#Setting the GET parameters on the URL
parameters = {"address": address_wanted, "key":api_key}
paramsurl = urllib.parse.urlencode(parameters)

#Generating the complete URL. Printing it in order to check if it's correct.
queryurl = serviceurl.strip() + paramsurl.strip()
print("DATA URL: ", queryurl)

#Obtaining and reading the data
try :
    data_read = urllib.request.urlopen(queryurl , context=ctx).read()
    data = data_read.decode()
    # Parsing the data and looking for the field we want.
    jsondata = json.loads(data)
    print(jsondata)
    place_id = jsondata["results"][0]["place_id"]
    print("PLACE ID: ", place_id)
except:
    print("Error.....")
    print("-"*50)
    print(data)

1 Comment

Welcome on Stack Overflow, while this may answer the question, it is better to give explanations and not only code for your answer.
0
import json,ssl
import urllib.request,urllib.parse, urllib.error



# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE



#Stroring the given parameters
api_key = 42
serviceurl = "http://py4e-data.dr-chuck.net/json?"
# sample_address = "South Federal University"
data_address = "IIT KANPUR"
address_wanted = data_address

#Setting the GET parameters on the URL
parameters = {"address": address_wanted, "key":api_key}
paramsurl = urllib.parse.urlencode(parameters)

#Generating the complete URL. Printing it in order to check if it's correct.
queryurl = serviceurl.strip() + paramsurl.strip()
print("DATA URL: ", queryurl)

#Obtaining and reading the data
try :
    data_read = urllib.request.urlopen(queryurl , context=ctx).read()
    data = data_read.decode()
    # Parsing the data and looking for the field we want.
    jsondata = json.loads(data)
    print(jsondata)
    place_id = jsondata["results"][0]["place_id"]
    print("PLACE ID: ", place_id)
except:
    print("Error.....")
    print("-"*50)
    print(data)
DATA URL:  http://py4e-data.dr-chuck.net/json?address=IIT+KANPUR&key=42
{'results': [{'access_points': [], 'address_components': [{'long_name': 'Kalyanpur', 'short_name': 'Kalyanpur', 'types': ['political', 'sublocality', 'sublocality_level_1']}, {'long_name': 'Kanpur', 'short_name': 'Kanpur', 'types': ['locality', 'political']}, {'long_name': 'Kanpur Nagar', 'short_name': 'Kanpur Nagar', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Uttar Pradesh', 'short_name': 'UP', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'India', 'short_name': 'IN', 'types': ['country', 'political']}, {'long_name': '208016', 'short_name': '208016', 'types': ['postal_code']}], 'formatted_address': 'Kalyanpur, Kanpur, Uttar Pradesh 208016, India', 'geometry': {'location': {'lat': 26.5123388, 'lng': 80.2329}, 'location_type': 'GEOMETRIC_CENTER', 'viewport': {'northeast': {'lat': 26.5136877802915, 'lng': 80.23424898029151}, 'southwest': {'lat': 26.5109898197085, 'lng': 80.23155101970849}}}, 'place_id': 'ChIJcb6oxAE3nDkRNoTDq4Do-zo', 'plus_code': {'compound_code': 'G66M+W5 Kalyanpur, jvs tower, Kanpur, Uttar Pradesh, India', 'global_code': '7MR2G66M+W5'}, 'types': ['establishment', 'point_of_interest', 'university']}], 'status': 'OK'}
PLACE ID:  ChIJcb6oxAE3nDkRNoTDq4Do-zo

1 Comment

While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation.
0
# In this program you will use a GeoLocation lookup API modelled after the
# Google API to look up some universities and parse the returned data.
import ssl
import urllib.request, urllib.parse, urllib.error
import json

api_key= False
# api_key='....'
if api_key is False:
    api_key=42
    serviceurl= 'http://py4e-data.dr-chuck.net/json?'

else:
    serviceurl='https://maps.googleapis.com/maps/api/geocode/json?'

## Ignore SSL certification
ctx=ssl.create_default_context()
ctx.check_hostname=False
ctx.verify_mode=ssl.CERT_NONE

while True:
    address= input('Enter Adderss: ')
    if len(address)< 1: break

    contents= dict()
    contents['address']=address
    if api_key is not False: contents['key']=api_key
    url= serviceurl+ urllib.parse.urlencode(contents)

    print('Retrieving:', url)
    access= urllib.request.urlopen(url, context=ctx)
    data= access.read().decode()
    print('Retrieved', len(data), 'characters')

    ## check--- working or not
    try:
        js= json.loads(data)
    except:
        None

    # check if status is OK
    if not js or 'status' not in js or js['status'] != 'OK':
        print('========Failure To Retrieve=========')
        print(data)
        continue

    ## For proper representation
    print(json.dumps(js, indent=4))
    ## Print various values
    loc= js['results'][0]['place_id']
    print('Loc', loc)
    addr= js['results'][0]['formatted_address']
    print('Address of', address,'is:',addr)
    lati= js['results'][0]['geometry']['location']['lat']
    long= js['results'][0]['geometry']['location']['lng']
    print('Latitude:',lati,'\nLongitude:',long)

1 Comment

code only doesn't answer the question so that you could come up with an explanation
0

Using urllib to open and collect data from URL. JSON to parse the data and load in JavaScript. We will get the result, i.e. place id using placeid = js['results'][0]['place_id'].

import urllib.request, urllib.parse, urllib.error
import json
import ssl

api_key = False
# If you have a Google Places API key, enter it here
# api_key = 'AIzaSy___IDByT70'
# https://developers.google.com/maps/documentation/geocoding/intro

if api_key is False:
    api_key = 42
    serviceurl = 'http://py4e-data.dr-chuck.net/json?'
else :
    serviceurl = 'https://maps.googleapis.com/maps/api/geocode/json?'

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

while True:
    address = input('Enter location: ')
    if len(address) < 1: break

    parms = dict()
    parms['address'] = address
    if api_key is not False: parms['key'] = api_key
    url = serviceurl + urllib.parse.urlencode(parms)

    print('Retrieving', url)
    uh = urllib.request.urlopen(url, context=ctx)
    data = uh.read().decode()
    print('Retrieved', len(data), 'characters')

    try:
        js = json.loads(data)
    except:
        js = None

    if not js or 'status' not in js or js['status'] != 'OK':
        print('==== Failure To Retrieve ====')
        print(data)
        continue


    placeid = js['results'][0]['place_id']

    print('Place id', placeid)

3 Comments

Please explain how your answer solves the problem. See How To Answer
using urllib to open and collect data from url. Json to parse the data and load in js. we will get the result i.e. place id using, placeid = js['results'][0]['place_id'].
Thanks! The explanation should be added to your answer, though, not as comment ;-)
0

The reason you are unable to get the program to work is because you are missing the key and when you run your program they say its: Missing/incorrect key = parameter (it is an easy number to guess) ...

and i guess as a joke they made it 42 which in The Hitchhiker's Guide to the Galaxy is the meaning of life.

1 Comment

I'd suggest showing the entire working code snippet along with your explanation of why and where the code is not working.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.