2017-08-07 60 views
1

我正在为我的天气应用程序编写脚本。我有以下存储在文件JSON:python json TypeError:字符串索引必须是整数

"{\"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}" 

我的代码:

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

任何帮助,将不胜感激:

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 

当我运行的功能我得到以下错误。

因为是被要求在评论,这里是我的全码:

#!/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 
+0

[TypeError:字符串索引在解析JSON,Python?时必须是整数](https:// stackoverflow。com/questions/32229546/typeerror-string-indices-must-be-integers-while-parsing-json-python) – pkqxdd

+3

该代码不会给出该错误;作为发布,它工作得很好。请显示您的实际代码和完整输出(包括打印件)。 –

+0

您可以用image_id = data1 ['weather']打印image_id吗?什么是输出? – Toandd

回答

0

的问题是在你的“ 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 
} 

(这是相当打印,不需要换行符/制表)

为什么你的文件不正确?

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

取而代之,您使用json.dump(),它旨在将数据输出为json文件。 它就是这样。它会创建一个json文件,其中包含您所提供的一个字符串。

只是

outfile.write(data) 

取代你

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

线,它应该工作。

+0

我得到我的'api.openweathermap.org'的json。我用我的get_current_weather()函数获取它并将其存储到文件save_to_file(data,file_name)函数中。 – bitUp

+0

@bitUp更新了答案。 – Baldrickk

+0

它的工作。谢谢 – bitUp

相关问题