python json TypeError:字符串索引必须是整数

时间:2017-08-07 10:17:52

标签: python json

我正在为我的天气应用编写脚本。我在文件中存储了以下json:

"{\"coord\":{\"lon\":21.01,\"lat\":52.23},\"weather\":[{\"id\":801,\"main\":\"Clouds\",\"description\":\"few clouds\",\"icon\":\"02d\"}],\"base\":\"stations\",\"main\":{\"temp\":21,\"pressure\":1023,\"humidity\":43,\"temp_min\":21,\"temp_max\":21},\"visibility\":10000,\"wind\":{\"speed\":2.6,\"deg\":20},\"clouds\":{\"all\":20},\"dt\":1502098200,\"sys\":{\"type\":1,\"id\":5374,\"message\":0.002,\"country\":\"PL\",\"sunrise\":1502075224,\"sunset\":1502129710},\"id\":756135,\"name\":\"Warsaw\",\"cod\":200}"

我的代码:

def get_image(json_file):

    json_file = "{}/{}".format(jsons_save_path, json_file)

    f = open(json_file, 'r')
    echo2 = f.read()
    data1 = json.loads(echo2)
    f.close()

    print(data1)
    print(type(data1))

    image_id = data1['weather'][0]['icon']
    print(image_id)

    return

运行该函数时出现以下错误:

  File "./get_weather.py", line 79, in get_image
image_id = data1['weather'][0]['icon']
TypeError: string indices must be integers

任何帮助都将不胜感激。

正如评论中所述,这是我的完整代码:

#!/usr/bin/env python3

import json
import http.client
import os
from shutil import copyfile


key = '...'
city_id = '756135'

conn = http.client.HTTPConnection('api.openweathermap.org')
payload = "{}"

jsons_save_path = '/shares/scripts/weather/jsons'

def get_current_weather():

conn.request("GET", "/data/2.5/weather?id=%s&units=metric&APPID=%s" % (city_id, key), payload)
res = conn.getresponse()
data = res.read()

data = data.decode("utf-8")

# print(json.loads(data))
save_to_file(data, 'current.json')
get_image('current.json')

return

def get_5_days():

conn.request("GET", "/data/2.5/forecast?id=%s&units=metric&APPID=%s" % (city_id, key), payload)
res = conn.getresponse()
data = res.read()

data = data.decode("utf-8")

# print(json.loads(data)) 
save_to_file(data, 'forecast.json')

return

def save_to_file(data, file_name):

tmp_file_name = "{}/{}.tmp".format(jsons_save_path, file_name)
final_file = "{}/{}".format(jsons_save_path, file_name)

with open(tmp_file_name, 'w') as outfile:
    json.dump(data, outfile, ensure_ascii=False, separators=(',', ':'))
    print("json files saved to tmp")

g = open(tmp_file_name, 'r')
echo = g.read()
g.close()

try:
    test_json = json.loads(echo)
    print('json is fine')
    copyfile(tmp_file_name, final_file)
except ValueError as e:
    print('invalid json with error: %' % e)
    return None

return

def get_image(json_file):

json_file = "{}/{}".format(jsons_save_path, json_file)

f = open(json_file, 'r')
echo2 = f.read()
data1 = json.loads(echo2)
f.close()

print(data1)
print(type(data1))

image_id = data1['weather'][0]['icon']
print(image_id)

return

if __name__ == '__main__':
    get_current_weather()
    get_5_days()

我收到错误:

./get_weather.py 
json files saved to tmp
json is fine
{"coord":{"lon":21.01,"lat":52.23},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"base":"stations","main":{"temp":21,"pressure":1023,"humidity":43,"temp_min":21,"temp_max":21},"visibility":10000,"wind":{"speed":2.6},"clouds":{"all":0},"dt":1502100000,"sys":{"type":1,"id":5374,"message":0.0081,"country":"PL","sunrise":1502075226,"sunset":1502129707},"id":756135,"name":"Warsaw","cod":200}

  

追踪(最近一次呼叫最后一次):

File "./get_weather.py", line 85, in <module>
get_current_weather()
File "./get_weather.py", line 27, in get_current_weather
get_image('current.json')
File "./get_weather.py", line 79, in get_image
image_id = data1['weather'][0]['icon']
TypeError: string indices must be integers

1 个答案:

答案 0 :(得分:1)

问题出在你的&#39; json&#39;文件。 实际存储的是一个字符串,加载json数据。

它确实作为有效的json验证,因为它自己的上的字符串是有效的json,因此json解析器不会抛出错误。

所以你正在做的是加载文件的内容并将其解析为json。这提供了一个字符串作为数据,并且这不能用字符串索引,就像你试图做的那样(因为它不是一个字典)。

您的文件应如下所示:

{"coord":{"lon":21.01,"lat":52.23},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"base":"stations","main":{"temp":21,"pressure":1023,"humidity":43,"temp_min":21,"temp_max":21},"visibility":10000,"wind":{"speed":2.6,"deg":20},"clouds":{"all":20},"dt":1502098200,"sys":{"type":1,"id":5374,"message":0.002,"country":"PL","sunrise":1502075224,"sunset":1502129710},"id":756135,"name":"Warsaw","cod":200}

(在一条线上)
或者:

{
    "coord": {
        "lon": 21.01,
        "lat": 52.23
    },
    "weather": [{
        "id": 801,
        "main": "Clouds",
        "description": "few clouds",
        "icon": "02d"
    }],
    "base": "stations",
    "main": {
        "temp": 21,
        "pressure": 1023,
        "humidity": 43,
        "temp_min": 21,
        "temp_max": 21
    },
    "visibility": 10000,
    "wind": {
        "speed": 2.6,
        "deg": 20
    },
    "clouds": {
        "all": 20
    },
    "dt": 1502098200,
    "sys": {
        "type": 1,
        "id": 5374,
        "message": 0.002,
        "country": "PL",
        "sunrise": 1502075224,
        "sunset": 1502129710
    },
    "id": 756135,
    "name": "Warsaw",
    "cod": 200
}

(这是非常印刷的,不需要换行/制表)

为什么你的档案不正确?

您正在做的是从api获取json数据作为字符串。此时,将其保存到文件中,只需要编写即可。

相反,您使用json.dump()用于将数据输出为json文件。 它就是这样。它创建一个json文件,其中只包含您提供的一个字符串。

只需更换

即可
json.dump(data, outfile, ensure_ascii=False, separators=(',', ':'))

对齐
outfile.write(data)

它应该有用。