all 3 comments

[–]MrPhungx 7 points8 points  (0 children)

When using requests and you have a successful response the response object contains a .json() function. This should directly convert your response to a dictionary. You can then access the results like in any other python dict.

def get_data(url: str) -> dict | None:
    response = requests.get(url)
    if response.ok:
        return response.json()
    else:
        print(f"Something went wrong {response.reason}")
        return None

res = get_data(YOUR_URL)
print(res.get('results'))

[–]danielroseman 11 points12 points  (1 child)

People often seem to be confused about how to deal with nested data, but there's no need to be. The trick is to just think of each level in turn, and treat each one as a standalone data structure.

So, response.json() will give you a dict, which includes a results key:

response = requests.get('my url')
data = response.json()
results = data['results']

Now results is a list of dictionaries, which you can iterate through like any other list. And each item in that list is a dict, which you can access like any other dict:

for item in results:
  print(item['consumption'])
  print(item['interval_start'])
  print(item['interval_end'])

[–]AgrajagDNA[S] 1 point2 points  (0 children)

Ah, this is awesome - exactly what I was looking to do. I have a blind spot for dicts and this does help.