Python NoneType 对象不可下标

标签 python json api

我正在尝试这段代码,并在以 lat、lng 和 location 开头的行中收到错误。有人可以帮忙吗?

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)

谢谢, 阿伦

最佳答案

错误,NoneType object is not subscriptable 意味着您尝试执行以下操作:

None[something]

如果发生在这一行:js["results"][0]["geometry"]["location"]["lat"],则意味着js["results"][0]["geometry"]["location"]["lat"] 不存在,即沿着该路径的某些内容评估为 None。

例如,如果 jsNone,则尝试计算 None["results"] 将失败。

或者,如果 js["results"][0]None,则尝试执行 None["geometry"] 将失败> 等等

顺便说一句,js 很可能是 None,因为你确实有这个:

except: js = None

关于Python NoneType 对象不可下标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34445401/

相关文章:

python - 在递归期间将值字符串化而不是打印它们

python - 使用子进程模块将双引号传递给来自 Python 的命令

python - 将单词拆分为字母字典 rxpy

python - 如何使用 python 脚本将 JSON 数据转换为 PDF

api - 如何从 Office 365 REST API 检索 ItemAttachment 内容?

php - 无法为 api 路由 laravel 设置 cookie

python - 在 python 请求中使用转义引号查询 Elasticsearch

ios - dispacth_sync与dispatch_async:iOS JSON解析

json - d3 - 无法从 json 请求返回数据?

python-3.x - neo4j - python 驱动程序,服务不可用