Filtering information from . JSON

Asked

Viewed 69 times

-2

I have the following script:

import json
import requests


def clima_semana():

    requisicao = requests.get('http://api.openweathermap.org/data/2.5/forecast?q=Rio de Janeiro&appid=233183ebc19d6700af2a1192a9c4bf74')
    previsao = json.loads(requisicao.text)

    return previsao['list'][0]['weather'][0]['description']

This function consumes a 5-day, 3-in-3-hour weather forecast API, but I only need the days' time description, at one time only. Notice how I had to index to get to the result! And this is only the first day, the structure is monstrous (lists within dictionaries that contain more dictionaries, etc).

How do I make one get just the information I need? Is there any other technique to solve this problem? The running time has also become super slow.

  • 1

    Who dictates the return of JSON is the API, if that endpoint is not serving you, maybe you can consume some other: https://openweathermap.org/api

  • 2

    Don’t let the API key exposed the view is public and may make misuse of it.

1 answer

0

Can you be more clear about what you need from this Json? Can it be any time of a certain day ? It has to be a specific time ?

You can encapsulate your logic in another function:

def GetDescricaoDoClima(dia, hora):
    return previsao['list'][dia]['weather'][hora]['description']

Day and time will be the position in the json lists. Good luck!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.