0

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.

1
  • 2
    You want if "last-disconnection-time" in item, not in json_array. Commented May 28, 2020 at 14:07

1 Answer 1

1

You need to check if "last-disconnection-time" is in item. json_array is your entire list. item is a dictionary where you want to find out if the key exists.

if "last-disconnection-time" in item:
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.