0

I'm trying to effectively allocate a doc's size, based on the size of the file saved in flash of ESP8266. Is there a way?

For example: file.size() X 1.5

2
  • 1
    I would think it very much depends on what the content is. If you have a lot of string data then it can correlate quite well. If you have a lot of numeric data then I would imagine the internal representation could be a lot smaller than the textual file representation of the same data.
    – Majenko
    Jun 21, 2022 at 11:20
  • @Majenko Since some parameter files are stored on flash (which also can be change in future), one size's can be 256, and other is 1250. My goal is not to allocate max of all
    – guyd
    Jun 21, 2022 at 11:22

1 Answer 1

4

There is unfortunately no way to predict the size of the JsonDocument from the file size alone.

As a workaround, I suggest that you allocate a very large memory pool and shrink it after deserialization; like so:

DynamicJsonDocument doc(ESP.getMaxAllocHeap());
deserializeJson(doc, file);
doc.shrinkToFit();

Indeed, this program consumes more memory than strictly required, but only for a fraction of a second.

See also:

4
  • Is only for DynamicJsonDocument?
    – guyd
    Jun 21, 2022 at 11:50
  • 1
    @guyd shrinkToFit is available in BasicJsonDocument, too. But not in JsonDocument or StaticJsonDocument. See the docs to determine which one to use in your use case.
    – orithena
    Jun 21, 2022 at 12:23
  • 1
    Depending on what is actually being done, the filtering feature may also be helpful.
    – timemage
    Jun 21, 2022 at 15:35
  • 2
    @guyd, you asked how to determine the document size at run time, so StaticJsonDocument is not an option. Jun 22, 2022 at 7:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.