WXforum.net

Weather Software => RaspberryPI Weather Software => Topic started by: Scott216 on April 24, 2019, 11:04:43 AM

Title: Extract Weather Underground json value using python
Post by: Scott216 on April 24, 2019, 11:04:43 AM
Weather Underground changed their API recently.  I'm trying to get rain data from my own station. When I do a get request, I get this back from WU:

{"observations":[{"stationID":"KVTWESTD3","obsTimeUtc":"2019-04-24T12:36:03Z","obsTimeLocal":"2019-04-24 08:36:03","neighborhood":"Mt. Snow/Suntec Forest","softwareType":"RPi-Moteino","country":"US","solarRadiation":null,"lon":-72.88607788,"realtimeFrequency":null,"epoch":1556109363,"lat":42.94797134,"uv":null,"winddir":298,"humidity":76,"qcStatus":1,"imperial":{"temp":44,"heatIndex":44,"dewpt":37,"windChill":41,"windSpeed":6,"windGust":15,"pressure":25.00,"precipRate":0.00,"precipTotal":0.07,"elev":1932}}]}

I'm trying to extract just the precipTotal value.  My old code looked like this:
Code: [Select]
response = requests.get(getUrl, timeout=10).json()
daily_rain = float(response['current_observation']['precip_today_in'])

I played replaced ['current_observation']['precip_today_in'] with a few variations I hoped would work, but I couldn't figure it out.  I know very little about json formats and I'm pretty new at python also.  Any suggestions?

Title: Re: Extract Weather Underground json value using python
Post by: droiddk on April 24, 2019, 01:57:53 PM
Hi Scott

This will do it:

Code: [Select]
import json

json_file = '{"observations":[{"stationID":"KVTWESTD3","obsTimeUtc":"2019-04-24T12:36:03Z","obsTimeLocal":"2019-04-24 08:36:03","neighborhood":"Mt. Snow/Suntec Forest","softwareType":"RPi-Moteino","country":"US","solarRadiation":null,"lon":-72.88607788,"realtimeFrequency":null,"epoch":1556109363,"lat":42.94797134,"uv":null,"winddir":298,"humidity":76,"qcStatus":1,"imperial":{"temp":44,"heatIndex":44,"dewpt":37,"windChill":41,"windSpeed":6,"windGust":15,"pressure":25.00,"precipRate":0.00,"precipTotal":0.07,"elev":1932}}]}'

weather_dictionary = json.loads(jsonfile)

precipTotal = weather_dictionary["observations"][0]['imperial']['precipTotal']

print(precipTotal)

Python is great :-)

Regards
Title: Re: Extract Weather Underground json value using python
Post by: Scott216 on April 24, 2019, 03:29:21 PM
Thanks droiddk.  It's working now.