Missing element - help json python3

Viewed 23

I'm new to Python and using Python3 to display the data from my weather station The problem I have is it used to work perfectly until I got a replacement station.

I found the problem

In the weather data sent there are 3 fields (not sure of the correct name) but they are

lightning_strike_last_distance 

lightning_strike_last_distance_msg 

lightning_strike_last_epoch 

In my new station these fields are completely missing as there has been no lightning since I got the new one

As a result the station display just doesn't parse the weather data as those fields are not there.

How can I get the program to check if those fields/elements or whatever the correct name is, and if they are there parse them as usual

but if they are not there to skip those and move onto the next section

This is the relevant section of code

lightning_strike_last_distance = forecast_json["current_conditions"]["lightning_strike_last_distance"]
lightning1 = lightning_strike_last_distance*0.621371 #Convert kph to mph
data.lightning_strike_last_distance = "{0:.2f} miles".format(lightning1)

lightning_strike_last_epoch = forecast_json["current_conditions"]["lightning_strike_last_epoch"]
data.lightning_strike_last_epoch = time.strftime("%d-%m-%Y %H:%M:%S", time.localtime(lightning_strike_last_epoch))

How can I fix it so the program skips those 3 elements/sections if they are missing?

1 Answers

try following pattern:

lightning_strike_last_distance = forecast_json["current_conditions"]["lightning_strike_last_distance"] if "lightning_strike_last_distance" in forecast_json["current_conditions"] else None

It will set lightning_strike_last_distance to the value if it is present, and set it to None if it is not present. Repeat that pattern for all other assignements.

to test it quickly try :

data = {"a":{"b":1,},}
valueB = data["a"]["b"] if "b" in data["a"] else None
valueC = data["a"]["c"] if "c" in data["a"] else None
print (valueB)
print (valueC)
Related