Python:无法解决的错误消息

时间:2016-01-05 05:35:56

标签: python python-3.5

我是python的新手。我正在使用python 3.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'  

1 个答案:

答案 0 :(得分:1)

只需要告诉python将其获取的字节对象解码为字符串。 这可以通过使用decode函数来完成。

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"])