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

时间:2016-06-20 23:22:20

标签: 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()

2 个答案:

答案 0 :(得分:5)

HTTPResponse object返回的urlopen读取bytes数据(原始二进制数据),而不是str数据(文本数据),而json模块工作与str。您需要知道(或检查标头以确定)用于收到的数据的编码,并在使用decode之前适当json.loads

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

data = webUrl.read()

为:

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

它应该解决你的问题。

答案 1 :(得分:0)

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

尝试使用urllib3并执行以下导入:

from urllib import urlopen

希望这是解决问题的方法

相关问题