2017-08-07 59 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

相關問題