JSONBufferWriter - how big should buf be?

i have an argon and send every couple of seconds some measured data.
at the moment i just use:
$measuredTemp;$measuredHumidity, like: 23;45, meaning: 23°C and 45% Humidity.
This is not so good because i’d like to have now much more values (about 10) and i am very sure ill face some mis-interpretation when i continue in that way, so i thought ill go with json because then i can address every value its own identifier.

but i have some problems understand how big “buf” should be.
when i want to send a string like: {“curTemp”:“30”, “curHum”: “40”}
how big should buf be?

buf from https://docs.particle.io/reference/device-os/firmware/argon/#jsonwriter
do i have to only count the values inside curTemp and curHum (in that case 4 char arrays, means buf = 4) or do i have to add everything meaning 32 chars + \0 ?

i have now the following code, it works but it feels somehow ugly to define a buf size and not having this dynamic, or is this common practice to do so?

char buf[JSON_BUF_SIZE] = {0};

    Measure measure = measureData();
    JSONBufferWriter writer(buf, sizeof(buf) - 1);

    writer.buffer()[std::min(writer.bufferSize(), writer.dataSize())] = 0;

    Particle.publish("data", String(buf), PRIVATE);

It’s the whole size of the encoded JSON, including the {} and any necessary double quotes and any space characters. It would be wise to make it a big bigger, just in case, since case the temperature becomes 3 digits or other things that affect the size. It can be bigger, say make it 64 bytes, it just can’t be smaller.

It’s not set dynamically because the JSON would have to be encoded twice, once to figure out how big it is, and a second to actually do it. And dynamically resizing the memory blocks is not a particularly fast or efficient way to do it.

1 Like

ok thanks, i have it now fixed at 600 just to make sure i wont get any trouble… maybe i’ll calculate that a bit more precise (guess 300 bytes is already enough).
it would be nice to have an object like:
JsonBuilder jsonBuilder = new JsonBuilder();
jsonBuilder.add(“prefTemp”, prefTemp);

and in the end just a: jsonBuilder.toString();

that would be awesome :smiley:
but guess it is how it is because of performance reasons