Gary
Gary

Reputation: 591

How to access data within Class Dict type?

I am trying to use specific weather data, which is in json format, and access certain parts of the data with a Python3 script. The actual data is not yet available online yet so I am using a sample provided of the json format. Here is the json file contents:

    "observations": [{
        "stationID": "KNCCARY89",
        "obsTimeUtc": "2019-02-04T14:53:14Z",
        "obsTimeLocal": "2019-02-04 09:53:14",
        "neighborhood": "Highcroft Village",
        "softwareType": "GoWunder 1337.9041ac1",
        "country": "US",
        "solarRadiation": 436.0,
        "lon": -78.8759613,
        "realtimeFrequency": null,
        "epoch": 1549291994,
        "lat": 35.80221176,
        "uv": 1.2,
        "winddir": 329,
        "humidity": 71,
        "qcStatus": 1,
        "imperial": {
            "temp": 53,
            "heatIndex": 53,
            "dewpt": 44,
            "windChill": 53,
            "windSpeed": 2,
            "windGust": null,
            "pressure": 30.09,
            "precipRate": 0.0,
            "precipTotal": 0.0,
            "elev": 413
        }
    }]
}

Here is the simple python script I am using to access this sample json data from a file on my Raspberry:

import json
from pprint import pprint

with open('data.json') as f:
    weather = json.load(f)

pprint(weather)

The data prints out nicely but I have been struggling using the embedded data!

When I query the type "type(weather)" the answer is "

The only query that seems to work is "pprint(weather['observations']) which shows all of the json data below 'observations', but I cannot figure out how to get lower than this!

Do I have to convert the data to another 'type'?

Upvotes: 0

Views: 50

Answers (1)

GeorgPoe
GeorgPoe

Reputation: 352

weather['observations'] seems to be an array with a single element in the JSON above. In Python, that weather['observations'] should thus be a list, and to access its first element, you would write

weather['observations'][0]

From that, you should be able to access the subelements, e.g.

weather['observations'][0]['stationID']

Upvotes: 1

Related Questions