为什么会出现错误 "the JSON object must be str, not 'bytes'",我该如何解决?

Why is it giving me the error, "the JSON object must be str, not 'bytes'", and how do I fix it?

我正在学习有关如何使用 JSON 对象 (link: https://www.youtube.com/watch?v=Y5dU2aGHTZg) 的教程。当他们 运行 代码时,他们没有出错,但我出错了。是跟Python版本不同还是什么有关?

from urllib.request import urlopen
import json

def printResults(data):
    theJSON = json.loads(data)
    print (theJSON)

def main():
    urlData ="http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson"

    webUrl = urlopen(urlData)
    print(webUrl.getcode())
    if (webUrl.getcode()==200):
        data = webUrl.read()
        printResults(data)
    else:
        print ("You failed")

main()

HTTPResponse object returned from urlopen 读取 bytes 数据(原始二进制数据),而不是 str 数据(文本数据),而 json 模块使用 str.您需要知道(或检查 headers 以确定)用于接收数据的编码,并在使用 json.loads.

之前适当地 decode

假设它是 UTF-8(大多数网站都是),您只需更改:

data = webUrl.read()

至:

data = webUrl.read().decode('utf-8')

它应该可以解决您的问题。

我认为他们使用了不同版本的 urllib

尝试使用 urllib3 并像这样导入:

from urllib import urlopen

希望这能解决您的问题