skip to Main Content

I’m working on a REST API assignment in uni which should be simple, but I’ve become stuck and have been going round in circles for hours.

I’ve been tasked with writing python code which ‘consumes’ JSON data from an API. Scope and Easy enough, right? The scope is up to me, so I have decided to keep it simple.

  1. Get data JSON from: here
  2. Parse it into a python list.
  3. Iterate through the list to display the key value pairs for multiple objects.

I thought json.loads() would parse my JSON data into a Python dictionary so that I could use items() in a for loop to produce the key value pairs, but I can only achieve the following:

I can do this in a manner using enumerate() on the list, but it does not format the results the way I would like.

I’ve used .items() in a for loop with my_dict = {"name": "Alice", "age": 30, "city": "New York"} successfully in another file – no problems at all there! The JSON response from the url is wrapped i and I thought it would be far easier to convert it than it is!

I feel I’m missing something extremely obvious here put cannot put my finger on it.

Could someone offer any advice? Code is below.

import json
import requests

url = "https://api.openbrewerydb.org/v1/breweries?by_city=miami&per_page=3"
response = requests.get(url)
print("nhttp status code: ",  response.status_code, "- ", response.reason)

json_data = json.loads(response.text)
print("JSON data type:", type(json_data))

print('nResults using index method')
json_dict = json_data[0]
for key, value in json_dict.items():
print(key, ": ", value,)

print('nResults using enumerate method')
for key, value in enumerate(json_data):
print("{} : {} ".format(key, value))

2

Answers


  1. The JSON response from the given API is a list of dictionaries. Therefore, when you do json_data[0], you are accessing the first dictionary in the list.

    Try this! This modified code iterates through the list of breweries and then iterates through each brewery’s key-value pairs. The enumerate method is used to display the index along with the brewery data in a formatted manner

    import json
    import requests
    
    url = "https://api.openbrewerydb.org/v1/breweries?by_city=miami&per_page=3"
    response = requests.get(url)
    print("nhttp status code: ", response.status_code, "- ", response.reason)
    
    json_data = json.loads(response.text)
    print("JSON data type:", type(json_data))
    
    print('nResults using index method')
    for brewery in json_data:
        for key, value in brewery.items():
            print(key, ": ", value)
    
    print('nResults using enumerate method')
    for index, brewery in enumerate(json_data):
        print(f"Brewery {index + 1}: {brewery}")
    
    
    Login or Signup to reply.
  2. You don’t need to use the json module to parse the response. Just use the functionalities of requests:

    json_data = requests.get(url).json()
    

    To print the response you could, for example, do this:

    for json_dict in json_data:  # Iterate through the list of JSON objects
        for key, value in json_dict.items():  # Display the key value pairs for each object
            print(key, ": ", value)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search