您的位置:首页 > 编程语言 > Python开发

Python.Calling a JSON API

2016-07-24 21:10 691 查看
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.

Please run your program to find the place_id for this location:
Universidad Nacional de Colombia

Hint: The first seven characters of the place_id are
"ChIJ92o ..."

Python源码:

import urllib
import json

serviceurl = 'http://python-data.dr-chuck.net/geojson?'

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

url = serviceurl + urllib.urlencode({'sensor':'false', 'address': address})
print 'Retrieving', url
uh = urllib.urlopen(url)
data = uh.read()
print 'Retrieved',len(data),'characters'

try: js = json.loads(str(data))
except: js = None
if 'status' not in js or js['status'] != 'OK':
print '==== Failure To Retrieve ===='
continue

place_id = js["results"][0]["place_id"]
print 'place_id',place_id
break

运行结果:
Enter location: Universidad Nacional de Colombia
Retrieving http://python-data.dr-chuck.net/geojson?sensor=false&address=Universidad+Nacional+de+Colombia place_id ChIJ92ouU_A3y5ERtjaGNPTPUGY
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: