【问题标题】:Python TypeError while converting JSON转换 JSON 时出现 Python TypeError
【发布时间】: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


【解决方案1】:

它确实以字典的形式返回,我只是愚蠢并称它错误。

【讨论】:

    猜你喜欢
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    相关资源
    最近更新 更多