Get Length of object in octects

Question:

I am needing to calculate the length of a dictionary in octects to conform to the BUFR standard which states:

Total length of BUFR message, in octets (including Section 0)

I have been able to find bytes, but not information for decoding octects.
To get bytes I would do:

sys.getsizeof(json_list)
Asked By: Jordan

||

Answers:

sys.getsizeof() will give you the size of an object in memory. But from your description, it sounds like you’re looking for the length of some serialization (into a message) of the dictionary.

It looks like you’re using JSON, and that makes sense. For example using json.dumps():

json_string = json.dumps(your_dict)

The next question is how do you get the length (in octets) of that string.

Well len(json_string) will give you the number of characters, but for most encodings, the number of bytes required to transmit those characters will be different.(Docs)

So first you need to encode your string to bytes, then use the length of the resulting bytes object:

len(json_string.encode(<your encoding>))

Which will give you the number of octets needed to transmit that dictionary.

Note: any other requirements of the message, such as headers, delimiters, escaping, formatting, etc will be in addition to this number.

Answered By: jedwards
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.