Python判断一个JSON文件是否为空

admin Python评论258字数 480阅读模式

首先,你需要导入`json`模块:

import json

然后,使用`json`模块的`load()`方法将JSON文件加载为Python对象。如果加载后得到的对象为空,表示JSON文件为空。

def is_json_file_empty(file_path):
   with open(file_path, 'r') as file:
       json_data = json.load(file)
       if json_data:
           return False
       else:
           return True

最后,通过传入JSON文件的路径调用该函数即可判断JSON文件是否为空:

json_file_path = "path_to_json_file.json" # 替换为你的JSON文件路径
is_empty = is_json_file_empty(json_file_path)
if is_empty:
    print("JSON文件为空")
else:
    print("JSON文件不为空")

请注意,这个方法假设你的JSON文件已经存在且格式正确。如果文件不存在或者文件格式不正确,可能会引发异常。在实际使用中,你可能需要添加相应的异常处理代码。

版权声明:文章图片资源来源于网络,如有侵权,请留言删除!!!
admin
  • 本文由 发表于 2023年9月14日 14:42:58
  • 转载请务必保留本文链接:https://www.58pxe.com/11079.html
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: