Read an bytearray from json

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
Lebowski
Posts: 7
Joined: Fri Dec 25, 2020 7:07 am

Read an bytearray from json

Post by Lebowski » Thu May 13, 2021 3:47 pm

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

karfas
Posts: 33
Joined: Sat Jan 16, 2021 12:53 pm

Re: Read an bytearray from json

Post by karfas » Thu May 13, 2021 10:13 pm

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.
My repositories: https://github.com/karfas

peterjohnee1
Posts: 1
Joined: Tue Oct 06, 2020 2:54 am
Contact:

Re: Read an bytearray from json

Post by peterjohnee1 » Sat May 15, 2021 8:09 am

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!

User avatar
pythoncoder
Posts: 5217
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Read an bytearray from json

Post by pythoncoder » Sat May 15, 2021 8:57 am

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.
Peter Hinch

Post Reply