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'  

person user2625433    schedule 05.01.2016    source источник


Ответы (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"])
person AbdealiJK    schedule 05.01.2016
comment
Большое тебе спасибо. Теперь работает нормально. - person user2625433; 05.01.2016
comment
Примите ответ, если он работает. - person AbdealiJK; 05.01.2016