我正在从一个多嵌套的json文件中读取.我已经创建了一个用于从json获取特定密钥的类,然后将其创建到一个数据帧中.
现在,如果密钥存在,则一切都按预期工作,并且找不到密钥时,我会得到以下错误
TypeError:‘NoneType’对象不可订阅
下面是一个样例json和代码快照
output = {"records":[{
"ID":{
"$":"123456"
},
"Records":{
"ChildRecord":{
"Address":[
{
"$": "24 Street"
}
]
}
}
},{
"ID":{
"$":"456789"
},
"Records":{
"ChildRecord":{
"Address":[
{
"$": "57 New Town"
}
]
}
}
}]}
identifier = [o.get('ID').get('$') for o in output['records']]
address = [o.get('Records').get('ChildRecord').get('Address')[0].get('$') for o in output['records']]
print(identifier,'identifier')
print(address,'address')
由于密钥存在,因此我得到以下输出
identifier ['123456','456789']
address ['24 Street','57 New Town']
If the "Address" key is not present in one of the record then I get the type error, TypeError:‘NoneType’对象不可订阅. How to overcome this issue and get the output as
identifier ['123456','456789']
address ['24 Street',None]
此外,在某些情况下,我会在多个密钥中获取地址
"Address":[
{
"$": "57 New Town"
},
{
"$": "New Castle Road"
},
{
"$": "PO Box 309"
}
]
有没有办法将整个地址读作
['24 Street','57 New Town, New Castle Road, PO Box 309']