【问题标题】:Python - Skip over key if it doesn't exist in json arrayPython - 如果 json 数组中不存在键,则跳过键
【发布时间】:2020-05-28 13:57:36
【问题描述】:

我有一个很大的 json 数组,列出了某些键值对。数组中的每个元素应如下所示:

{
   "id" : "tmp3269879718695646867",
   "owner" : "johndoe",
   "x11-display" : ":7",
   "x11-authority" : "/run/user/1676/dcv/tmp3269879718695646867.xauth",
   "num-of-connections" : 0,
   "creation-time" : "2019-05-15T20:05:46.170274Z",
   "last-disconnection-time" : "2019-07-19T15:14:37.349168Z"
 },

然后我在末尾附加一个开始方括号和一个结束方括号,以使其成为有效的 JSON。有时,数组中有大约 100 个元素。由于软件升级,如果用户没有断开连接,则最后一次断开连接时间键不会出现在此输出上。我想要做的是遍历数组中的每个元素,但如果最后断开时间键不存在,则跳过整个元素。到目前为止,这是我在循环中所拥有的:

for item in json_array:
        session_details = {"owner":None, "num-of-connections":None, "last-disconnection-time":None}
        session_details['owner'] = item['owner']
        user = item['owner']
        session_details['num-of-connections'] = item['num-of-connections']
        session_details['last-disconnection-time'] = item['last-disconnection-time']
        # Format date
        ...

我想做的是每次循环时检查该项目。像这样的:

for item in json_array:
        session_details = {"owner":None, "num-of-connections":None, "last-disconnection-time":None}
        session_details['owner'] = item['owner']
        user = item['owner']
        session_details['num-of-connections'] = item['num-of-connections']
        if "last-disconnection-time" in json_array:
                session_details['last-disconnection-time'] = item['last-disconnection-time']
        else:
                print("last-disconnection-time does not exist in this array item")
        # Format date
        ...

但是在运行脚本时我仍然得到 KeyError。

【问题讨论】:

  • 你想要if "last-disconnection-time" in item,而不是in json_array

标签: python arrays json


【解决方案1】:

您需要检查“last-disconnection-time”是否在项目中。 json_array 是您的整个列表。 item 是一个字典,你想在其中找出键是否存在。

if "last-disconnection-time" in item:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多