1

I am working on Python 3 and storing only required data from a JSON payload, sometimes the payload is not consistent and the values I am storing may not be present. My code works fine when all the values are present in the payload, sharing a sample data and code. I would like to assing Null or None when a value is not present in the payload. Can anyone please help me in resolving this issue.
Sample Data

data = 
{
            "Session": {
                "@displayName": "1212",
                "@id": 1212,
                "anchorIpAddress": {
                    "address": "0.0.0.0"
                },
                "apMacAddress": {
                    "octets": "111111111"
                },
                "algorithm": "OPENSYSTEM",
                "bytesReceived": 1000,
                "bytesSent": 100
            }
        },
        {
            "Session": {
                "@displayName": "1111",
                "@id": 1111,
                "anchorIpAddress": {
                    "address": "0.0.0.0"
                },
                "algorithm": "OPENSYSTEM",
                "bytesReceived": 234,
                "bytesSent": 20
            }
        },
        {
            "Session": {
                "@displayName": "1313",
                "@id": 1313,
                "apMacAddress": {
                    "octets": "14312312"
                },
                "algorithm": "OPENSYSTEM",
                "bytesReceived": 39735,
                "bytesSent": 8308
            }
        }
}  

Code

        clients = json.loads(json.dumps(data, indent=2))
        client1 = {}

    for client in clients:
        client1["display"] = client['Session']['@display']
        client1["id"] = client['Session']['@id']
        client1["anchorIpAddress"] = client['Session']['anchorIpAddress']['address']
        client1["apMacAddress"] = client['Session']['apMacAddress']['octets']
        print(client1)  

Error

   client1["apMacAddress"] = client['clientSessionsDTO']['apMacAddress']['octets']
   KeyError: 'apMacAddress'  

Expected Result

{
display: 1212,
id: 1212,
anchorIpAddress: "0.0.0.0",
apMacAddress: "111111111"
},
{
display: 1212,
id: 1212,
anchorIpAddress: "0.0.0.0",
apMacAddress: Null
},
{
display: 1313,
id: 1313,
anchorIpAddress: Null,
apMacAddress: "14312312"
}

1 Answer 1

1

Maybe

client1["apMacAddress"] = client.get('clientSessionsDTO',{}).get('apMacAddress',{}).get('octets', None)

could help?

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.