JSON string vs bytearray

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
danielm
Posts: 167
Joined: Mon Oct 05, 2015 12:24 pm

JSON string vs bytearray

Post by danielm » Sun Nov 13, 2016 6:55 pm

What is the best approach when attempting to construct JSON string repeatedly in every cycle of main loop in case one wants to avoid memory allocation in every cycle? Could formatted string be somehow directly stored in pre-allocated bytearray?

The JSON string always contains same keys, but lenght(number of digits) of values may vary in every cycle.

User avatar
dhylands
Posts: 3455
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: JSON string vs bytearray

Post by dhylands » Sun Nov 13, 2016 8:09 pm

If you know the maximum number of digits, then you could allocate that in the JSON array. You could use a memoryview to map directly to those bytes. When you format the numbers use leading spaces but always make them the length of your max number, for example:

Code: Select all

>>> '{:6d}'.format(123)
'   123'
If you really want to reduce memory allocation you should write your own integer to string conversion routine, although that may not be required since we're only talking about a small allocation now.

EDIT: If you put unique numbers/ids in for each place that you want a number, you can use str.find to get the index for creating the memory view.

Post Reply