Parsing openweathermap.org

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
matt42
Posts: 7
Joined: Sat Apr 25, 2020 4:10 am

Parsing openweathermap.org

Post by matt42 » Sat Apr 25, 2020 4:33 am

Hi there,
new MP user with an esp32.
MicroPython v1.12-388-g388d419ba

I am trying to get info from api.openweathermap.org API and parse it to get some individual values. Here is my code:

Code: Select all

import urequests, ujson
def url():
    r = urequests.get("https://api.openweathermap.org/data/2.5/onecall?<snipped>")
    ud = r.text
    raw = ujson.loads(ud)
    t = raw.get('current').get('temp')
    w = raw.get('current').get('weather')
    print(t)
    print(w)
url()
The openweathermap URL provides data like this:

Code: Select all

{"timezone":"Australia/Melbourne","current":{"dt":1587788262,"sunrise":1587761706,"sunset":1587800335,"temp":20.58,"feels_like":18.94,"pressure":1015,"humidity":61,"dew_point":12.8,"uvi":3.5,"clouds":87,"wind_speed":3.58,"wind_deg":57,"wind_gust":7.15,"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}]},"hourly": <snipped>
The output of my program is this:

Code: Select all

20.34
[{'id': 804, 'icon': '04d', 'main': 'Clouds', 'description': 'overcast clouds'}]
How do I get the result of "description"? It is embedded between "[ ]" and the normal ".get" does not work. It seems to be a dictionary trapped in a list and i'm not sure how to handle it.

thanks in advance,

Matt

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: Parsing openweathermap.org

Post by jimmo » Sat Apr 25, 2020 4:47 am

matt42 wrote:
Sat Apr 25, 2020 4:33 am
It seems to be a dictionary trapped in a list and i'm not sure how to handle it.
Yep, it's exactly that.

So

Code: Select all

w = raw.get('current').get('weather')
w is a list of dictionaries. So w[0] is the first element of the list, then w[0].get('description') will be what you want. (You can use len(w) to see if there are any entries, or even just "if w:").

I looked briefly at their docs, it's not clear if there's always at least one entry in the "weather" list (i.e. can you always assume that w[0] exists). Also it seems possible that there could be more than one.

matt42
Posts: 7
Joined: Sat Apr 25, 2020 4:10 am

Re: Parsing openweathermap.org

Post by matt42 » Sat Apr 25, 2020 5:08 am

Thanks Jimmo, easy when you know how. Your explanation makes alot of sense and now I can access the data I need :)

cheers
Matt

Post Reply