Page 1 of 1

Read an bytearray from json

Posted: Thu May 13, 2021 3:47 pm
by Lebowski
Hi,

unfortunately it's not possible to store bytearrays in json-files. If i use the string-representation of an bytearray, e .g (b\xe5V\xb5\x01<: i get (bxe5V\xb5x01<: after loading the file.
If i escape the backslashes (b\\xe5V\\xb5\\x01<: i get the same string (with double-backslashes) after loading the file.

How to get single backslashes or is there any other proper way to store bytearrays in python.

Thank you

Re: Read an bytearray from json

Posted: Thu May 13, 2021 10:13 pm
by karfas
I don't think that there exists any standard how binary data needs to be encoded in JSON.

An approach I have seen often is base64-encod binary data in JSON strings.

Re: Read an bytearray from json

Posted: Sat May 15, 2021 8:09 am
by peterjohnee1
karfas wrote:
Thu May 13, 2021 10:13 pm
cookie clicker
I don't think that there exists any standard how binary data needs to be encoded in JSON.
An approach I have seen often is base64-encod binary data in JSON strings.
Good!

Re: Read an bytearray from json

Posted: Sat May 15, 2021 8:57 am
by pythoncoder
You can always "cheat" and copy the data to a list:

Code: Select all

b = bytearray(x for x in range(256))  # Test with all possible values
s = ujson.dumps([x for x in b])
z = bytearray(x for x in ujson.loads(s))
Not specially efficient, but then JSON never is. But the recipient has to do this explicit conversion. The same drawback applies to using base64, of course.

There are other serialisation options such as pickle.