skip to Main Content

I am trying to isolate several variables from a JSON file I have taken from https://api.weatherapi.com/v1/forecast.json?q=’s-Hertogenbosch&days=3&alerts=yes&aqi=yes&key=X

Key removed for safety reasons.

Therefore I use the following code:

import json

response = urlopen(url)
  
weer_data = json.loads(response.read())

location = weer_data['location']['name']
temp_current = weer_data['current']['temp_c']

alert_source = list(weer_data['alerts']['alert']['headline'])

location and temp_current can be isolated and stored as variable without any problem. But the alert_source gives me problems because there are multiple values with the same header ‘headline’ in the JSON file. The part that gives problems looks like this:

"alerts": {
    "alert": [
      {
        "headline": "Koninklijk Meteorologisch Instituut van Belgiƫ",
        "msgtype": "",
      },
      {
        "headline": "Deutscher Wetterdienst",
        "msgtype": "",

Anyone who can help me with storing the ‘headline’ as variable?

2

Answers


  1. {
        "alert": [{
            "headline": "Koninklijk Meteorologisch Instituut van Belgiƫ",
            "msgtype": "",
        }, {
            "headline": "Deutscher Wetterdienst",
            "msgtype": "",
        }]
    }
    
    # if you want to get only first headline
    print(a["alert"][0]["headline"])
    
    # get all the headline and store it in a list
    headlines = [item["headline"] for item in a["alert"]]
    print(headlines)
    

    Try this code, I think it will work.

    Login or Signup to reply.
  2. You can use a dict comprehension.

    alert_source = {a['headline'] : a['msgtype'] for a in weer_data['alerts']['alert']}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search