duplicate json

Hi everyone!

I have a problem, I need to update a json string, but when I change the value and serialize again, the string is duplicated, and updates only in the duplicated string. How to update without doing this duplication? Sorry, I have no experience with json on Arduino.

Here is the code and the result:

code:

#include <ArduinoJson.h>

String json = "{\"-a1\":{\"name\":\"filipe\",\"keycode\":\"00001\"},\"-a2\":{\"name\":\"kevin\",\"keycode\":\"00002\"}}";
bool test = true;
StaticJsonDocument<200> doc;

void setup() {
  Serial.begin(115200);
  deserializeJson(doc, json);
  Serial.println(json);

}

void loop() {
  // put your main code here, to run repeatedly:
  if(test)
  {
    if(doc["-a1"]["name"] == "filipe")
    {
      doc["-a1"]["name"] = "ana";
      serializeJson(doc, json);
    }
    Serial.println(json);
    test = false;
  }
}

result (Monitor serial):

{"-a1":{“name”:“filipe”,“keycode”:“00001”},"-a2":{“name”:“kevin”,“keycode”:“00002”}}

{"-a1":{“name”:“filipe”,“keycode”:“00001”},"-a2":{“name”:“kevin”,“keycode”:“00002”}}{"-a1":{“name”:“ana”,“keycode”:“00001”},"-a2":{“name”:“kevin”,“keycode”:“00002”}}

Thanks!

Check the docs for serialize:

This function treats String and std::string as streams: it doesn’t replace the content, it appends to the end.

You will need to clear your string before you use it.

Thank you, @wildbill

It works :slight_smile:

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.