I am writing a python object with json.dump. But I want to only write if the file size is less than 10KB.
How can estimate the size of an object before writing?
CodePudding user response:
Convert the JSON to a string, then use sys.getsizeof(). It returns the size in bytes, so you can divide by 1024
if you want to compare it to a threshold value in kilobytes.
sys.getsizeof(json.dumps(object))
Sample usage:
import json
import sys
x = '{"name":"John", "age":30, "car":null}'
y = json.loads(x)
print(sys.getsizeof(json.dumps(y))) # 89
Edit:
As mentioned in this thread, objects have a higher size in memory. So subtract 49
from the size to get a better estimate.
print(sys.getsizeof(json.dumps(y)) - 49)
CodePudding user response:
len(json.dumps(object))
is the answer after testing it.
I used the code below on an existing JSON file, which is 69961
bytes in size according to my file browser, and the code below.
sys.getsizeof()
returns a higher number than the actual size of the resulting file at the end...
import json
import sys
import os
with open("somejson.json") as infile:
data = json.load(infile)
print(len(json.dumps(data)))
print(sys.getsizeof(json.dumps(data)))
with open("somejson.json", "w") as outfile:
json.dump(data, outfile)
print(os.path.getsize("somejson.json"))
output
69961
70010
69961