无法从 json api 打印想要的项目
Unable to print wanted item from json api
我正在尝试从 json url 文件中打印 'temp' 项目。问题是,我不能只输入 print(item['temp']
如果我这样做,我会收到此错误:
TypeError: string indices must be integers
所以我想我必须改用整数,这就是我所做的。但是当它
打印出我得到的结果:
"f
c
这没有任何意义,无论我输入什么数字,我都会得到 2 个字母形式的结果。
代码如下:
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])
data['weather']
是一个 字典 ,直接在字典上循环会生成该字典中的键。这里每个键都是一个字符串; 'curren_weather'
或 'forecast'
。因此,item[0]
取每个键的第一个字母,所以你最终打印 f
和 c
:
>>> for item in data['weather']:
... print(item)
...
curren_weather
forecast
>>> for item in data['weather']:
... print(item[0])
...
c
f
我认为您想在 curren_weather
引用的列表中打印字典列表的 'temp'
键:
for curr in data['weather']['curren_weather']:
print(curr['temp'] + curr['temp_unit'])
我也添加了 temp_unit
值;以上输出:
15c
我正在尝试从 json url 文件中打印 'temp' 项目。问题是,我不能只输入 print(item['temp']
如果我这样做,我会收到此错误:
TypeError: string indices must be integers
所以我想我必须改用整数,这就是我所做的。但是当它 打印出我得到的结果:
"f c
这没有任何意义,无论我输入什么数字,我都会得到 2 个字母形式的结果。
代码如下:
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])
data['weather']
是一个 字典 ,直接在字典上循环会生成该字典中的键。这里每个键都是一个字符串; 'curren_weather'
或 'forecast'
。因此,item[0]
取每个键的第一个字母,所以你最终打印 f
和 c
:
>>> for item in data['weather']:
... print(item)
...
curren_weather
forecast
>>> for item in data['weather']:
... print(item[0])
...
c
f
我认为您想在 curren_weather
引用的列表中打印字典列表的 'temp'
键:
for curr in data['weather']['curren_weather']:
print(curr['temp'] + curr['temp_unit'])
我也添加了 temp_unit
值;以上输出:
15c