【发布时间】:2019-09-20 14:33:25
【问题描述】:
我这里有一些代码,用于我的 Slack Bot:
import pyowm
owm.set_API_key('Key Here')
observation = owm.weather_at_id(4744326)
w = observation.get_weather()
jsondata= w.get_temperature('fahrenheit') # Here is our JSON Data.
response = (json.loads(jsondata))
print(response)
我要转换的 JSON 是:
{"temp": 47.05, "temp_max": 50.0, "temp_min": 42.8, "temp_kf": null}
当我运行它时,我收到以下错误:
TypeError: the JSON object must be str, bytes or bytearray, not dict
有什么建议吗?
【问题讨论】:
-
看起来
jsondata已经是一个字典,所以不需要使用json库来解析它 -
以后,请发送minimal reproducible example,包括带有回溯的完整错误消息。 (在这种情况下,这意味着发布
w.get_temperature('fahrenheit')的输出。) -
docs 很清楚
get_temperature返回一个dict,而不是原始 json。 -
@aws_apprentice 根据您的回复,我尝试了
response = ("The current temperature (Fahrenheit) is:",jsondata[1]),得到:Exception has occurred: KeyErrorFile "D:\my codes\2022bot.py", line 65, in handle_command response = ("The current temperature (Fahrenheit) is:",jsondata[1]) File "D:\my codes\2022bot.py", line 85, in <module> handle_command(command, channel) -
您尝试的问题是
1不是字典中的有效键,也许您可能需要重新考虑如何访问字典中的元素?
标签: python json openweathermap