Python JSON解析处理缺少的值
我正在使用Python3,只存储JSON负载中所需的数据,有时负载不一致,并且存储的值可能不存在。当所有值都存在于有效负载中,共享一个示例数据和代码时,我的代码工作正常。当有效负载中不存在值时,我希望分配Null或None。谁能帮我解决这个问题。Python JSON解析处理缺少的值,python,json,python-3.x,Python,Json,Python 3.x,我正在使用Python3,只存储JSON负载中所需的数据,有时负载不一致,并且存储的值可能不存在。当所有值都存在于有效负载中,共享一个示例数据和代码时,我的代码工作正常。当有效负载中不存在值时,我希望分配Null或None。谁能帮我解决这个问题。 样本数据 data = { "Session": { "@displayName": "1212",
样本数据
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
}
}
}
代码
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)
错误
client1["apMacAddress"] = client['clientSessionsDTO']['apMacAddress']['octets']
KeyError: 'apMacAddress'
预期结果
{
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"
}
也许吧
你能帮忙吗
client1["apMacAddress"] = client.get('clientSessionsDTO',{}).get('apMacAddress',{}).get('octets', None)