为什么它给我错误,"JSON对象必须是str,而不是'bytes'",我该如何解决?

And*_* Ho 0 python json urllib

我正在学习如何使用JSON对象的教程(链接: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()
Run Code Online (Sandbox Code Playgroud)

Sha*_*ger 5

在模块使用时,从读取数据(原始二进制数据)而不是数据(文本数据)返回的HTTPResponse对象.您需要知道(或检查标头以确定)用于接收数据的编码,并在使用之前进行适当的编码.urlopenbytesstrjsonstrdecodejson.loads

假设它是UTF-8(大多数网站都是),你可以改变:

data = webUrl.read()
Run Code Online (Sandbox Code Playgroud)

至:

data = webUrl.read().decode('utf-8')
Run Code Online (Sandbox Code Playgroud)

它应该解决你的问题.