Python:无法恢复的错误消息

2024-06-16 08:50:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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'  

Tags: theinpyimportjsondatamainurllib2
1条回答
网友
1楼 · 发布于 2024-06-16 08:50:07

只需告诉python将它放入字符串中的bytes对象解码。 这可以通过使用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"])

相关问题 更多 >