简体   繁体   English

python和json,错误-TypeError:字符串索引必须为整数

[英]python and json, Error - TypeError: string indices must be integers

I Learn kivy for making android app. 我学习了制作Android应用程序的知识。 so I read the 'Creating Apps in Kivy' book. 所以我读了《在Kivy中创建应用程序》一书。 I encountered into error when I follow instructions. 遵循说明时遇到错误。

My python code is below. 我的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()

And my Error is 我的错误是

 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

And json content is 和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}

How can I solve it?? 我该如何解决?

You are only getting 1 record as a dict so you don't need the loop. 您仅获得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

You're taking the indice of a string, not the dictionary that you think you are, here 您使用的是字符串的索引,而不是您认为的字典

for i in data2:
    cities = ['{} ({})'.format(i['name'],i['sys']['country'])]
    self.search_results.item_strings = cities

As tdelaney mentioned in the comments, you're iterating through the dict and then trying to take the indice of a string inside of it. 正如tdelaney在评论中提到的那样,您要遍历dict,然后尝试在其中放入字符串的索引。

See this post as well. 也请参阅此帖子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM