I have big json array that lists out certain key value pairs. Each element in the array should look like this:
{
"id" : "tmp3269879718695646867",
"owner" : "johndoe",
"x11-display" : ":7",
"x11-authority" : "/run/user/1676/dcv/tmp3269879718695646867.xauth",
"num-of-connections" : 0,
"creation-time" : "2019-05-15T20:05:46.170274Z",
"last-disconnection-time" : "2019-07-19T15:14:37.349168Z"
},
I then attach a beginning square braket and an end square bracket at the end to make it valid JSON. Sometimes, there are around 100 elements in the array. Due to an software upgrade, if the user has not disconnected then the last-disconnection-time key does not appear on this output. What I want to do is loop over each element in the array, but skip the entire element if the last-disconnection-time key does not exist. This is what I have so far in the loop:
for item in json_array:
session_details = {"owner":None, "num-of-connections":None, "last-disconnection-time":None}
session_details['owner'] = item['owner']
user = item['owner']
session_details['num-of-connections'] = item['num-of-connections']
session_details['last-disconnection-time'] = item['last-disconnection-time']
# Format date
...
What I would like to do is check for the item each time it loops. Something like this:
for item in json_array:
session_details = {"owner":None, "num-of-connections":None, "last-disconnection-time":None}
session_details['owner'] = item['owner']
user = item['owner']
session_details['num-of-connections'] = item['num-of-connections']
if "last-disconnection-time" in json_array:
session_details['last-disconnection-time'] = item['last-disconnection-time']
else:
print("last-disconnection-time does not exist in this array item")
# Format date
...
However I still get the KeyError when running the script.
if "last-disconnection-time" in item, notin json_array.