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

发布于 2021-01-29 17:47:07

我在使模块“ 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:JSON对象必须为str,而不是’bytes’
”。我是Python的新手,因此很可能是一个非常简单的解决方案。感谢这里的任何帮助。

关注者
0
被浏览
156
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    除了忘记解码之外,您只能读取 一次 响应。已经调用过.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()呼叫将告诉您服务器认为使用了哪些字符集。

    演示:

    >>> 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}}
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看