Created
April 19, 2021 10:28
-
-
Save dalemyers/f776508ed8aeb6c86c6b96c2f6f37d6f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_entry_size(entry: Any) -> int: | |
"""Get the approximate size an entry will be in JSON. | |
Notes: Doesn't check for escaped characters in strings, so the size returned | |
will essentially always be a lower bound. | |
:param entry: The entry to get the size of | |
:returns: A size in bytes | |
""" | |
size = 0 | |
if isinstance(entry, dict): | |
size += 1 # { | |
for index, key in enumerate(entry.keys()): | |
value = entry[key] | |
size += 1 + len(key) + 1 # Quotes | |
size += 1 # Colon | |
size += get_entry_size(value) | |
if index < len(entry) - 1: | |
size += 1 # Comma | |
size += 1 # } | |
elif isinstance(entry, list): | |
size += 1 # [ | |
for index, value in enumerate(entry): | |
size += get_entry_size(value) | |
if index < len(entry) - 1: | |
size += 2 # Comma | |
size += 1 # ] | |
elif isinstance(entry, str): | |
size += 1 # Quote | |
size += len(entry) | |
size += 1 # Quote | |
elif isinstance(entry, bool): | |
size += 4 if entry else 5 | |
elif isinstance(entry, int): | |
if entry == 0: | |
size += 1 # Just count direct | |
else: | |
if entry < 0: | |
entry = -entry | |
size += 1 # For minus sign | |
size += int(math.log10(entry) + 1) | |
elif isinstance(entry, float): | |
size += len(str(entry)) | |
else: | |
raise ValueError() | |
return size |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment