【问题标题】:Python - handle missing key from json dataPython - 处理 json 数据中丢失的密钥
【发布时间】:2022-06-10 23:15:48
【问题描述】:

我有这个脚本,用于从 API 调用中提取一些数据。

# list of each api url to use
link =[]
#for every device id , create a new url link into the link list
for i in deviceIDList:
    link.append('https://website/v2/accounts/accountid/devices/'+i)

#create a list with all the different requests

deviceReq = []
for i in link:
    deviceReq.append(requests.get(i, headers=headers).json())


# write to a txt file
with open('masterSheet.txt', 'x') as f:
    for i in deviceReq:
        devices =[i['data']]
        for x in devices:
            models = [x['provision']]
            for data in models:
              sheet=(data['endpoint_model']+" ",x['name'])
              f.write(str(sheet)+"\n")

有些设备没有provision 键。

这是一些来自不同设备的示例数据。

假设我想获取 device_type 键值,而不是如果 provision 键不存在。

"data": {
        "sip": {
            "username": "xxxxxxxxxxxxxxxx",
            "password": "xxxxxxxxxxxxxxxx",
            "expire_seconds": xxxxxxxxxxxxxxxx,
            "invite_format": "xxxxxxxxxxxxxxxx",
            "method": "xxxxxxxxxxxxxxxx",
            "route": "xxxxxxxxxxxxxxxx"
        },

        "device_type": "msteams",
        "enabled": xxxxxxxxxxxxxxxx,
        "suppress_unregister_notifications": xxxxxxxxxxxxxxxx,
        "owner_id": "xxxxxxxxxxxxxxxx",
        "name": "xxxxxxxxxxxxxxxx", 
    }

我该如何处理丢失的钥匙?

【问题讨论】:

  • 像这样使用dict.get() x.get('provision', x.get('device_type'))
  • 你能发布完整的例子吗?
  • 这是一个完整的例子。如果 x['provision'] 抛出 KeyError,那么 x.get('provision') 不会,而是返回 None。如果键不存在,则第二个参数是默认值。

标签: python json


【解决方案1】:

您可以使用.get(key, defualt_value) 从字典中获取值,或者如果不存在,它将使用默认值,如下所示:

provision = x.get('provision', None)
if provision is None:
    provision = x.get('device_type')
models = [provision]

或者,如果您愿意,也可以在一行中执行相同的操作,而无需额外的 if 或赋值(尽管有些人可能会发现它更难以阅读和理解。

models = [x.get('provision', x.get('device_type'))]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2020-10-03
    • 2021-10-20
    • 2016-01-03
    相关资源
    最近更新 更多