【问题标题】:TypeError: list indices must be integers or slices, not str . while working with jsonTypeError:列表索引必须是整数或切片,而不是 str 。在使用 json 时
【发布时间】:2021-08-12 22:55:33
【问题描述】:

我正在使用 API 制作一个简单的天气应用程序。 我收到错误:列表索引必须是整数或切片,而不是 str。我知道问题出在哪里,但我不知道如何解决。我的代码是:

from django.shortcuts import render
import urllib.request
import json

在此处创建您的视图。

def index(request):

    if request.method == 'POST':
        city = request.POST['city']

        source = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+city+'&appid=5ba7df1f751428007642bf4e5f6c4c9a').read()
    list_of_data = json.loads(source)

        data = {
            "country_code": str(list_of_data['sys']['country']),
            "coordinate" : str(list_of_data['coord']['lon']) + ' '
            + str(list_of_data['coord']['lat']),
            "temp" : str(list_of_data['main']['temp']) + 'k',
            "pressure": str(list_of_data['main']['pressure']),
            "humidity": str(list_of_data['main']['humidity']),
            "weather" : str(list_of_data['weather']['description']),
        }
        print(data)
    else: 
        data = {}

    return render(request, 'main/index.html', data)`

问题出在数据字典的最后一行。我不知道怎么写。请帮我解决这个问题。

【问题讨论】:

    标签: python json python-3.x django django-views


    【解决方案1】:

    请改用list_of_data['weather'][0]['description']

    天气包含一个列表结构(注意在 JSON 的天气部分中使用方括号),其中有多个项目的选项。在大多数情况下,您只需要第一个,因此请使用 [0]

    【讨论】:

    • 成功了。谢谢。你能说出它起作用的原因吗?会很有帮助的。
    • @SaifKhan 我编辑了问题以解释原因。
    【解决方案2】:
    context = {
            "data": data
        }
    
    return render(request, 'main/index.html', context)
    

    这应该可以工作

    【讨论】:

      猜你喜欢
      • 2017-11-19
      • 2021-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 2021-11-28
      • 1970-01-01
      相关资源
      最近更新 更多