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

ocrdu
1,7953 gold badges12 silver badges24 bronze badges
asked Jun 21, 2022 at 11:09
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. Commented 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 Commented 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:

answered Jun 21, 2022 at 11:43
4
  • Is only for DynamicJsonDocument? Commented 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. Commented Jun 21, 2022 at 12:23
  • 1
    Depending on what is actually being done, the filtering feature may also be helpful. Commented 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. Commented Jun 22, 2022 at 7:51

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.