![](/img/trans.png)
[英]Python and JSON Error - TypeError: string indices must be integers
[英]python and json, Error - TypeError: string indices must be integers
我學習了制作Android應用程序的知識。 所以我讀了《在Kivy中創建應用程序》一書。 遵循說明時遇到錯誤。
我的python代碼如下。
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.network.urlrequest import UrlRequest
import json
import urllib
import urllib.request
import codecs
class AddLocationForm(BoxLayout):
search_input = ObjectProperty()
search_results = ObjectProperty()
def search_location(self):
search_template = 'http://api.openweathermap.org/data/2.5/' + 'weather?q={}&&APPID=d9733213314ecfdbd08f9753d38444bf'
search_url = search_template.format(self.search_input.text)
u = urllib.request.urlopen(search_url)
data = u.read().decode('utf-8')
print(type(data))
# request = UrlRequest(search_url, self.found_location)
self.found_location(data)
def found_location(self, data):
# reader = codecs.getreader("utf-8")
data2 = json.loads(data)
# data2 = reader(data).json()
print(data2)
for i in data2:
cities = ['{} ({})'.format(i['name'],i['sys']['country'])]
self.search_results.item_strings = cities
class WeatherApp(App):
pass
if __name__ == '__main__':
WeatherApp().run()
我的錯誤是
Traceback (most recent call last):
File "E:\Weather\main.py", line 52, in <module>
WeatherApp().run()
File "C:\Python34\lib\site-packages\kivy\app.py", line 828, in run
runTouchApp()
File "C:\Python34\lib\site-packages\kivy\base.py", line 487, in runTouchApp
EventLoop.window.mainloop()
File "C:\Python34\lib\site-packages\kivy\core\window\window_sdl2.py", line 619, in mainloop
self._mainloop()
File "C:\Python34\lib\site-packages\kivy\core\window\window_sdl2.py", line 362, in _mainloop
EventLoop.idle()
File "C:\Python34\lib\site-packages\kivy\base.py", line 330, in idle
self.dispatch_input()
File "C:\Python34\lib\site-packages\kivy\base.py", line 315, in dispatch_input
post_dispatch_input(*pop(0))
File "C:\Python34\lib\site-packages\kivy\base.py", line 221, in post_dispatch_input
listener.dispatch('on_motion', etype, me)
File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:7699)
File "C:\Python34\lib\site-packages\kivy\core\window\__init__.py", line 1030, in on_motion
self.dispatch('on_touch_down', me)
File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:7699)
File "C:\Python34\lib\site-packages\kivy\core\window\__init__.py", line 1046, in on_touch_down
if w.dispatch('on_touch_down', touch):
File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:7699)
File "C:\Python34\lib\site-packages\kivy\uix\widget.py", line 432, in on_touch_down
if child.dispatch('on_touch_down', touch):
File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:7699)
File "C:\Python34\lib\site-packages\kivy\uix\widget.py", line 432, in on_touch_down
if child.dispatch('on_touch_down', touch):
File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:7699)
File "C:\Python34\lib\site-packages\kivy\uix\behaviors\button.py", line 110, in on_touch_down
self.dispatch('on_press')
File "kivy\_event.pyx", line 714, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:7654)
File "kivy\_event.pyx", line 1224, in kivy._event.EventObservers.dispatch (kivy\_event.c:13497)
File "kivy\_event.pyx", line 1108, in kivy._event.EventObservers._dispatch (kivy\_event.c:12329)
File "C:\Python34\lib\site-packages\kivy\lang.py", line 1557, in custom_callback
exec(__kvlang__.co_value, idmap)
File "E:\Weather\weather.kv", line 89, in <module>
on_press: root.search_location()
File "E:\Weather\main.py", line 35, in search_location
self.found_location(data)
File "E:\Weather\main.py", line 43, in found_location
cities = ['{} ({})'.format(i['name'],i['sys']['country'])]
TypeError: string indices must be integers
和json內容是
{
"coord":{"lon":-123.12,"lat":49.25},
"weather":[{"id":800,"main":"Clear","description":"clearsky","icon":"02n"}],
"base":"stations",
"main":{"temp":265.29,"pressure":1022,"humidity":73,"temp_min":263.15,"temp_max":267.15 },
"visibility":48279,
"wind":{"speed":2.6,"deg":80},"clouds":{"all":5},"dt":1484230500,
"sys":{"type":1,"id":3359,"message":0.0149,"country":"CA","sunrise":1484237006,"sunset":1484267964},
"id":6173331,"name":"Vancouver","cod":200}
我該如何解決?
您僅獲得1條記錄作為dict,因此不需要循環。
def found_location(self, data):
# reader = codecs.getreader("utf-8")
data2 = json.loads(data)
# data2 = reader(data).json()
print(data2)
cities = ['{} ({})'.format(data2['name'],data2['sys']['country'])]
self.search_results.item_strings = cities
您使用的是字符串的索引,而不是您認為的字典
for i in data2:
cities = ['{} ({})'.format(i['name'],i['sys']['country'])]
self.search_results.item_strings = cities
正如tdelaney在評論中提到的那樣,您要遍歷dict,然后嘗試在其中放入字符串的索引。
也請參閱此帖子 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.