Blue Week Special Offer | Brighten your week!
days
hours
minutes
seconds

52-8 : Create Python Object - .JSON ( ) vs .CONTENT + JSON.LOADS

Screen Link:

Working With APIs In Python — Getting JSON From A Request | Dataquest

My Code:

Instead of using .json method , I tried to substitute it by using .content and .loads

My thinking was that if .json() converts content to python object, 
let me try using what i learnt earlier missions using 2 different steps. 
So I tried to get the content and then changed it to python object. 
However, I am getting an error. Please let me know what i did wrong below:


# Make the same request we did two screens ago.
parameters = {"lat": 37.78, "lon": -122.41}
response = requests.get("http://api.open-notify.org/iss-pass.json", params=parameters)

# Get the response data as a Python object.  Verify that it's a dictionary.
json_data_1 = response.content
json_data = json.loads(json_data1)
print(type(json_data_1))
print(type(json_data))
print(json_data)


first_pass_duration = json_data["response"][0]["duration"]

What actually happened:

TypeErrorTraceback (most recent call last)
<ipython-input-1-ed30d2bade8d> in <module>()
     12 # Get the response data as a Python object.  Verify that it's a dictionary.
     13 json_data_1 = response.content
---> 14 json_data = json.loads(json_data_1)
     15 print(type(json_data_1))
     16 print(type(json_data))

/usr/lib/python3.4/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    310     if not isinstance(s, str):
    311         raise TypeError('the JSON object must be str, not {!r}'.format(
--> 312                             s.__class__.__name__))
    313     if s.startswith(u'\ufeff'):
    314         raise ValueError("Unexpected UTF-8 BOM (decode using utf-8-sig)")

TypeError: the JSON object must be str, not 'bytes'

DQ’s solution is below :

parameters = {“lat”: 37.78, “lon”: -122.41}
response = requests.get(“http://api.open-notify.org/iss-pass.json”, params=parameters)

Get the response data as a Python object. Verify that it’s a dictionary.

json_data = response.json()
print(type(json_data))
print(json_data)
first_pass_duration = json_data[“response”][0][“duration”]

1 Like

The error is pretty straightforward.

loads() expects a string, but you pass bytes to it.

So, you first need to convert (decode) your json_data_1 to string first -

json_data_1.decode("utf-8")

When you use response.json(), you don’t have to consider the above because it decodes it for us, if needed. .json() is essentially the combination of what you were attempting to do.

thank you . Need to read up on the encodings