JSONWriter not performing as expected when passing to function

When passing a JSONBufferWriter to a function, I’m not getting the output I would expect.

Here’s a cut down example:

void setup() {
    char buf[622];
    memset(buf, 0, sizeof(buf));
    JSONBufferWriter writer(buf, sizeof(buf)-1);
    
    writer.beginObject();
    addToJSON(writer);
    writer.endObject();
    
    Particle.publish("JSON", String(buf), PRIVATE);
}

void addToJSON(JSONBufferWriter writer){
    writer.name("hello").value("world");
}

I would expect this to output {"hello":"world"}, but I get {}hello":"world". It seems like the order is getting messed up. Is this a bug? Or am I doing something wrong? Many thanks

Ahh, I’ve fixed this by passing a reference &writer to the function and then accessing it with writer->name. Would still be interested to know why the first way doesn’t work if anyone is a c++ expert though :slight_smile:

When not passing an object as reference you are creating a copy of the original via the copy operator which may not actually do what you want - to know exactly you’d need to investigate the implementation of the operator - although passing object copies around is not best practice anyhow :wink:
The next best thing to references would be passing an object pointer.

However, I think there is some issue with the implementation as I’d expect your result to be {} without the hello":"world" part.
addToJSON() only acts on a copy of the object which unfortunately also happens to share the same buffer as the original and hence places hello":"world" in that buffer, but the original does not know about the change of its buffer so it will end with an empty JSON expression followed by the residual entry of the copy in its buffer which hasn’t yet received its closing curly brace.

Ahhh I see. Thanks for the explanation, much appreciated:)

1 Like

can you post the code for this? I can’t visualize it.