Python:可以';无法解决

Python:可以';无法解决,python,python-3.5,Python,Python 3.5,我是python新手。我正在使用Python3.x。我已多次尝试更正此代码,但收到的错误消息很少。有人能帮我更正一下密码吗 import urllib.request as urllib2 #import urllib2 #import urllib2 import json def printResults(data): #Use the json module to load the string data into a directory theJSON = json.

我是python新手。我正在使用Python3.x。我已多次尝试更正此代码,但收到的错误消息很少。有人能帮我更正一下密码吗

import urllib.request as urllib2
#import urllib2 
#import urllib2
import json

def printResults(data):
    #Use the json module to load the string data into a directory
    theJSON = json.loads(data)
    #Now we can access the contents of json like any other python object
    if "title" in theJSON["metadata"]:
        print (theJSON["metadata"]["title"])

def main():

    #Define the varible that hold the source of the Url
    urlData= "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson"

    #Open url and read the data
    webUrl= urllib2.urlopen(urlData)
    #webUrl= urllib.urlopen(urldata)
    print (webUrl.getcode())
    if (webUrl.getcode() == 200):
        data= webUrl.read()
        #Print our our customized result
        printResults(data)
    else:
         print ("Received an error from the server, can't retrieve results  " + str(webUrl.getcode()))   

if __name__== "__main__":
    main()
以下是我得到的错误:

Traceback (most recent call last):
  File "C:\Users\bm250199\workspace\test\JSON_Data.py", line 30, in <module>
    main()
  File "C:\Users\bm250199\workspace\test\JSON_Data.py", line 25, in main
    printResults(data)
  File "C:\Users\bm250199\workspace\test\JSON_Data.py", line 8, in printResults
    theJSON = json.loads(data)
  File "C:\Users\bm250199\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 312, in loads
    s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'  
回溯(最近一次呼叫最后一次):
文件“C:\Users\bm250199\workspace\test\JSON\u Data.py”,第30行,在
main()
文件“C:\Users\bm250199\workspace\test\JSON\u Data.py”,第25行,在main中
打印结果(数据)
文件“C:\Users\bm250199\workspace\test\JSON\u Data.py”,第8行,在printResults中
theJSON=json.loads(数据)
文件“C:\Users\bm250199\AppData\Local\Programs\Python\Python35-32\lib\json\\ uuuuu init\uuuu.py”,第312行,加载
s、 _u_类________;名称____;)
TypeError:JSON对象必须是str,而不是“bytes”

只需告诉python将它得到的字节对象解码为字符串即可。 这可以通过使用
解码
功能来完成

theJSON = json.loads(data.decode('utf-8'))
您可以通过添加if条件使函数更加健壮,如:

def printResults(data):
    if type(data) == bytes: # Convert to string using utf-8 if data given is bytes
        data = data.decode('utf-8')

    #Use the json module to load the string data into a directory
    theJSON = json.loads(data)
    #Now we can access the contents of json like any other python object
    if "title" in theJSON["metadata"]:
        print (theJSON["metadata"]["title"])

非常感谢你。现在工作很好。如果有效,请接受答案。