Converting JSON list (from an API) into a python dictionary

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

Source link

Leave a Reply

Your email address will not be published. Required fields are marked *