Issue
I need to check if my JSON file contains data or only empty array. I am doing it in this way:
with open('example.json') as f:
data = json.load(f)
if not data:
do_my_stuff()
But my JSON files can be really huge and I do not want to load them all.
Can I check if file contains nothing but empty array in other way? Check if my file's weight is 2 bytes (isn't it lame?)?
Solution
You have to use os.path.getsize(path)
to find file size of a file.
You do not have to read file at all.
If JSON file is just 2 bytes, "[]" or "{}", it is an empty JSON object.
Based on some JSON usage principles, in this particular case it is sane and safe to presume that a 2 bytes long JSON string is an empty string, array or object ("", [], {}). A two digits number may be a valid JSON string but it is not what JSON is used for (you can use JSON library to load a single value like you can use a big crane to lift an egg).
If this [file size] does not fulfill your requirements you have to read the first 2 bytes and check if they are equal to '[]':
with open(filename, 'rb') as file:
if file.read(2) != '[]':
file.seek(0) # it may be redundant but it does not hurt
json.load(file)
Answered By - Elis Byberi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.