Python 如果JSON对象中不存在密钥,如何添加密钥
我有一个json数组,我迭代该数组并试图打印json对象的特定键和值,但我得到了KeyErrorPython 如果JSON对象中不存在密钥,如何添加密钥,python,Python,我有一个json数组,我迭代该数组并试图打印json对象的特定键和值,但我得到了KeyError employees = [ { "id":"101", "name": "abc", "mobile":"123" }, { "id": "102", "name": "xyz" } ] 我想在不存在“mobile”的json对象中添加键“mobile”。你能帮我一下吗,我如何在python中做到这一点?你的第二个employee对象没有“mobile”属性
employees = [
{
"id":"101",
"name": "abc",
"mobile":"123"
},
{
"id": "102",
"name": "xyz"
}
]
我想在不存在“mobile”的json对象中添加键“mobile”。你能帮我一下吗,我如何在python中做到这一点?你的第二个employee对象没有“mobile”属性,因此代码会产生一个错误。为避免出现这种情况,您可以使用
if
语句避免打印不存在的移动密钥:
对于员工中的员工:
如果员工中有“手机”:
打印(员工['mobile'])
还可以将该键添加到现有对象:
for employee in employees:
employee['mobile'] = '123'
print(employee['mobile'])
但下一次在提出问题之前,我建议做一些研究,因为这种问题已经被问过很多次了;) 这不是一个json数组,它是一个
dict
对象的list
列表…看看pythondict
的get
方法。在这种情况下,所有不正确的项的移动值都将是123,我只想在它不存在时添加
for employee in employees:
employee['mobile'] = '123'
print(employee['mobile'])
mobile = "mobile"
for employee in employees:
if mobile not in employee:
employee[mobile]=123999