Python JSON无法拉出并打印文本标识符

时间:2016-01-18 03:34:11

标签: python json

我试图拉出并打印出来的地方ID http://python-data.dr-chuck.net/geojson

这是我的代码:

SymfonyStyle

输出即时取消是正确的,但地点ID未打印。任何想法为什么?

2 个答案:

答案 0 :(得分:2)

与评论中指出的相同 - 如果您更改变量名称,则可以使用它:

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 ===='
        print data
        continue
    #print json.dumps(js, indent=4) # commented out to stop filling my screen with place names - easily put back in
    placeid = js['results'][0]['place_id']

    print "Place ID: ", placeid
    print placeid
    print address    # location not defined 

重要的一点是最后一行,它将变量名称更改为您在用户输入请求中声明的变量名称。

我使用了多伦多大学&#39;作为测试,没有问题。

答案 1 :(得分:0)

您无需检查系统是否识别了用户的位置。当您输入错误的位置时,您会收到错误密钥和有效位置列表。请检查一下。

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()
    # uncomment for debug...
    #print 'Retrieved',len(data),'characters'

    try: 
        js = json.loads(str(data))
    except:
        js = None
        print 'got exception'
        continue

    if "error" in js:
        print "Choose a location from the following list"
        for location in js["locations"]:
            print '   ', location
        continue

    if 'status' not in js or js['status'] != 'OK':
        print '==== Failure To Retrieve ===='
        print data
        continue
    print json.dumps(js, indent=4)
    placeid = js['results'][0]['place_id']

    print "Place ID: ", placeid
    print placeid