Question

I am trying to extract needed data from JSON data from Open weather maps API in Python (2.7)! JSON file looks something like this.

{u'calctime': 0.0331,
 u'cnt': 2,
 u'cod': u'200',
 u'list': [{u'clouds': {u'all': 75},
            u'coord': {u'lat': 45.551109, u'lon': 18.69389},
            u'distance': 0.001,
            u'dt': 1351870200,
            u'id': 3193935,
            u'main': {u'humidity': 93,
                      u'pressure': 1008,
                      u'temp': 287.15,
                      u'temp_max': 291.18,
                      u'temp_min': 287.15},
            u'name': u'Osijek',
            u'weather': [{u'description': u'broken clouds',
                          u'icon': u'04d',
                          u'id': 803,
                          u'main': u'Clouds'}],
            u'wind': {u'deg': 70, u'speed': 4.6}},
           {u'clouds': {u'all': 75},
            u'coord': {u'lat': 45.568611, u'lon': 18.61389},
            u'distance': 6.526,
            u'dt': 1351870200,
            u'id': 3187657,
            u'main': {u'humidity': 93,
                      u'pressure': 1008,
                      u'temp': 285.43,
                      u'temp_max': 287.15,
                      u'temp_min': 282.15},
            u'name': u'Visnjevac',
            u'weather': [{u'description': u'light intensity shower rain',
                          u'icon': u'09d',
                          u'id': 520,
                          u'main': u'Rain'}],
            u'wind': {u'deg': 70, u'speed': 4.6}}],
 u'message': u'Model=GFS-OWM, '}

This is weather data for two geographical points. I know how to extract single data from the both points (for example humidity or temperature) by using json package but problem is that I can not extract multiple data of the same type put from different geographical points. In this example I want to extract/print names of those points (osijek, visnjevac).

Is there a way to that with json encoder/decder?

Was it helpful?

Solution

What you have is not JSON, it is a Python object, so I am assuming you already passed the original JSON string through json.loads() or something similar.

To extract the 'name' values for each dictionary in the list of cities, you can use the following:

names = [city['name'] for city in data['list']]

Result:

>>> names
[u'Osijek', u'Visnjevac']

The assumes you have the content from your post in the variable data.

OTHER TIPS

I'd like to add to F.J's answer that, if you wanted to dynamicaly extract data for specific cities, you could do something like this:

cities = ['osijek', 'visnjevac']
cities_data = filter(lambda i: i['name'].lower() in cities, data['list'])

You might find useful my GitHub Python project PyOWM, which is a simple object-oriented client wrapper around the Open Weather Map web API.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top