首页 > 解决方案 > 检查json文件是否有条目

问题描述

我想看看我的 json 文件中是否有任何条目。

目前我的 json 文件如下所示:

{
}

我想检查用户是否已经在 json 文件中添加了一些东西(比如 ex "stackoverflow": "test")。

使用此代码,我可以列出文件中的所有对象

    with open("keys.json") as f:
        data = json.load(f)
        for obj in data:
            print(obj)

现在我想检查json文件是否为空,我想这样做:

    with open("keys.json") as f:
        data = json.load(f)
        for obj in data:
            if not obj:
                print(Fore.LIGHTRED_EX + "No sites/TOTP codes have been added yet, add one first.")

然而可悲的是,这不起作用,有什么想法吗?

标签: pythonjson

解决方案


要检查文件是否为空对象,根据定义,您不能对其进行迭代(没有可迭代的内容)

with open("keys.json") as f:
    data = json.load(f)

if not data:
    print("File is an empty structure") # empty dict or empty list

要处理大多数情况,您可以使用列表或字典

if not data:
    print("File is an empty structure") # empty dict or empty list

elif isinstance(data, list):
    for obj in data:
        print(obj)

elif isinstance(data, dict):
    for k, val in data.items():
        print(k, "=", val)

推荐阅读