Vitalynx Vitalynx - 2 months ago 14
JSON Question

Unable to print wanted item from json api

I'm trying to print the 'temp' item from a json urlfile. The problem is, I can't just type in

print(item['temp']

If i do I get this error:


TypeError: string indices must be integers


So I figured I had to use an integer instead, which is what I did. But when it
prints out the result I got this:

"f
c"

This doesn't make any sense, doesn't matter what number I type in I get a result in the form of 2 letters.

Here's the code:

import urllib.request
import json

url = urllib.request.urlopen("http://www.myweather2.com/developer/forecast.ashx?uac=fRnJKj3Xpi&output=json&query=SW1")
readurl = url.read()
json_obj = str(readurl, "utf-8")
data = json.loads(json_obj)

for item in data['weather']:
print(item[0])

Answer

data['weather'] is a dictionary, and looping directly over a dictionary produces the keys in that dictionary. Here each key is a string; either 'curren_weather' or 'forecast'. As such, item[0] takes the first letter of each of these keys, so you end up printing f and c:

>>> for item in data['weather']:
...     print(item)
...
curren_weather
forecast
>>> for item in data['weather']:
...     print(item[0])
...
c
f

I take it you want to print the 'temp' key of the list of dictionaries in the list referenced by curren_weather instead:

for curr in data['weather']['curren_weather']:
    print(curr['temp'] + curr['temp_unit'])

I added the temp_unit value too; the above outputs:

15c