Tips & Tricks: How to find a JSON object size in Python?

ยท

1 min read

Tips & Tricks: How to find a JSON object size in Python?

In this blog, you will learn how to find a JSON string object size in bytes using encode() or bytes() method in Python. We can also use these methods to find REST API JSON payloads size in Python.

To calculate the size, we first need to convert python objects into JSON strings using json.dumps().

import json
dictionary = {"test_1":"xyz", "test_2":"zyx"}   #python object
json_string = json.dumps(dictionary)

Encode the string object into byte object using encode("utf-8") or bytes(json_string, "utf-8") method. This is because directly using len() method would give us the number of key-value pairs. Here, for example, len(json_string) gives us 2 as the output as there are two key-value pairs.

If you want to know about utf-8, read this article.

The encode() method encodes the string. If nothing is specified then utf-8 is used and the same applies to the bytes() method.

byte_ = json_string.encode("utf-8")
# or byte_ = bytes(json_string, "utf-8")
print(byte_) 
# output: b'{"test_1":  "xyz",  "test_2":  "zyx"}'

Now, we can use len() method to find the length.

size_in_bytes = len(byte_)
# output: 34 (in bytes)

Thank you for reading this blog! ๐Ÿ˜‡

ย