-1

I am new to python. I am using python 3.x. I have tried to correct this code many times but I am getting few error messages. Can someone please help to correct me with the code?

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()

Here are the errors that I am getting:

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'  
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user2625433
  • 311
  • 2
  • 5
  • 6

1 Answers1

1

Just have to tell python to decode the bytes object it got into a string. This can be done by using the decode function.

theJSON = json.loads(data.decode('utf-8'))

You could make the function more robust by adding an if condition like:

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"])
AbdealiLoKo
  • 3,261
  • 2
  • 20
  • 36