Home > Software design >  extracting items from json with python
extracting items from json with python

Time:11-03

I made an api query which returns a json as response. I am trying to extract the temperature_2m for the first time in the list (2022-11-03T00:00) which is 5.7, not sure how to get it with python

api_query ={
    "latitude": 52.52,
    "longitude": 13.419998,
    "generationtime_ms": 0.36203861236572266,
    "utc_offset_seconds": 0,
    "timezone": "GMT",
    "timezone_abbreviation": "GMT",
    "elevation": 38.0,
    "hourly_units": {
        "time": "iso8601",
        "temperature_2m": "°C"
    },
    "hourly": {
        "time": [
            "2022-11-03T00:00",
            "2022-11-03T01:00"
           
        ],
        "temperature_2m": [
            5.7,
            5.2
           
        ]
    }
}

for key in api_query:
    temperature = api_query['hourly']['time'][0]['temperature_2m']
    print(temperature)

CodePudding user response:

This is not working:

temperature = api_query['hourly']['time'][0]['temperature_2m']

coz temperature is a sub attribute from "hourly" but not from "time"

you need instead:

for the temp:

temperature = api_query['hourly']['temperature_2m'][0]
print(temperature)

and for the time:

time = api_query['hourly']['time'][0]

here a Jupyter Notebook enter image description here

CodePudding user response:

temperature = api_query['hourly']['temperature_2m'][0]

  • Related