Dav*_*sjö 15 python python-3.x
我在模块'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
Run Code Online (Sandbox Code Playgroud)
通过命令行运行脚本时,我得到的错误是" TypeError:JSON对象必须是str,而不是'bytes' ".我是Python的新手,因此很可能是一个非常简单的解决方案.感谢这里的任何帮助.
Mar*_*ers 30
除了忘记解码外,您只能阅读一次响应.已经调用.read(),第二个调用返回一个空字符串.
.read()只调用一次,并将数据解码为字符串:
data = webURL.read()
print(data)
encoding = webURL.info().get_content_charset('utf-8')
JSON_object = json.loads(data.decode(encoding))
Run Code Online (Sandbox Code Playgroud)
该response.info().get_content_charset()调用告诉您服务器认为使用的字符集.
演示:
>>> 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}}
Run Code Online (Sandbox Code Playgroud)
当我自己研究时,你只需要使用decode('utf-8')函数,然后使用json.load()函数后提取为 json 格式。
>>> 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()
>>> JSON_object = json.loads(data.decode('utf-8'))
{'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}}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26819 次 |
| 最近记录: |