python - 检查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.")
然而可悲的是,这不起作用,有什么想法吗?
解决方案
要检查文件是否为空对象,根据定义,您不能对其进行迭代(没有可迭代的内容)
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)
推荐阅读
- javascript - 编写将项目添加到不同状态数组的函数时遇到问题
- vba - if 和 for 循环包含在 while 循环 VBA 中
- azure - 如何测量 Azure Function 冷启动时间
- r - R Highcharter:格式化工具提示
- php - 为什么不打印用户表单提交消息(在浏览器停止确认表单提交警报后)
- hibernate - JPQL org.hibernate.hql.internal.ast.QuerySyntaxException:意外令牌:第 1 行附近的联合
- ios - Google Cast SDK 无法在带有 wifi 的 Xcode 9.4 模拟器上运行,但可在以太网上运行
- cassandra - 删除一行需要多长时间?
- asp.net-web-api - 向 API 发送带有空参数的特定请求时遇到问题
- c# - 拳击不明显