python json 类型错误 : string indices must be integers

标签 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}

Traceback (most recent call last):

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

最佳答案

问题出在您的“json”文件中。 您实际上存储的是一个字符串,而不是一堆 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
}

(这是 pretty-print ,不需要换行符/制表)

为什么你的文件不正确?

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

相反,您可以使用 json.dump() 来将数据输出为 json 文件。 它就是这么做的。它会创建一个 json 文件,其中仅包含您提供的一个字符串。

只需更换您的

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

一致
outfile.write(data)

它应该可以工作。

关于python json 类型错误 : string indices must be integers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45544574/

相关文章:

python - PIL putpixels函数

python - 嵌套 for 循环搜索 2 个列表

python - 直方图的全局和局部最大值

javascript - 根据javascript中的键值合并两个json对象

python - 根据列名称将数据帧转换为 JSON

python - 从两个大小相等的 numpy 数组创建一个最小量值的数组

python - 如何在 Linux RHEL 6.6 上安装 docker-compose?

.net - 确保 .NET 中的 json 键是小写的

json - Ruby on Rails JSON.parse 意外 token 错误

javascript - 从 JSON 设置父子关系