gpt4 book ai didi

python - 使用 urllib.request 和 json 模块在 Python 中加载 JSON 对象

转载 作者:太空狗 更新时间:2023-10-29 17:24:08 33 4
gpt4 key购买 nike

我在使模块“json”和“urllib.request”在简单的 Python 脚本测试中协同工作时遇到问题。使用 Python 3.5,这里是代码:

import json
import urllib.request

urlData = "http://api.openweathermap.org/data/2.5/weather?q=Boras,SE"
webURL = urllib.request.urlopen(urlData)
print(webURL.read())
JSON_object = json.loads(webURL.read()) #this is the line that doesn't work

当通过命令行运行脚本时,我得到的错误是“TypeError:the JSON object must be str, not 'bytes'”。我是 Python 的新手,所以很可能有一个非常简单的解决方案。感谢这里的任何帮助。

最佳答案

除了忘记解码外,您只能读取响应一次。已经调用了 .read(),第二次调用返回一个空字符串。

仅调用一次.read(),并将数据解码为字符串:

data = webURL.read()
print(data)
encoding = webURL.info().get_content_charset('utf-8')
JSON_object = json.loads(data.decode(encoding))

response.info().get_content_charset() call告诉您服务器认为使用的是什么字符集。

演示:

>>> import json
>>> import urllib.request
>>> urlData = "http://api.openweathermap.org/data/2.5/weather?q=Boras,SE"
>>> webURL = urllib.request.urlopen(urlData)
>>> data = webURL.read()
>>> encoding = webURL.info().get_content_charset('utf-8')
>>> json.loads(data.decode(encoding))
{'coord': {'lat': 57.72, 'lon': 12.94}, 'visibility': 10000, 'name': 'Boras', 'main': {'pressure': 1021, 'humidity': 71, 'temp_min': 285.15, 'temp': 286.39, 'temp_max': 288.15}, 'id': 2720501, 'weather': [{'id': 802, 'description': 'scattered clouds', 'icon': '03d', 'main': 'Clouds'}], 'wind': {'speed': 5.1, 'deg': 260}, 'sys': {'type': 1, 'country': 'SE', 'sunrise': 1443243685, 'id': 5384, 'message': 0.0132, 'sunset': 1443286590}, 'dt': 1443257400, 'cod': 200, 'base': 'stations', 'clouds': {'all': 40}}

关于python - 使用 urllib.request 和 json 模块在 Python 中加载 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32795460/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com