bblanchon / ArduinoJson

📟 JSON library for Arduino and embedded C++. Simple and efficient.
https://arduinojson.org
MIT License
6.63k stars 1.1k forks source link

best way to create a sub document #2074

Closed briandilley closed 3 months ago

briandilley commented 3 months ago

Is there a better way of doing this?

    JsonDocument doc;

    doc["config"]["tmp"] = true; 
    doc["config"].remove("tmp");
    JsonObject configCtxDoc = doc["config"].as<JsonObject>(); 

    // this method adds stuff to the configCtxDoc
    this->configCtx.getConfiguration(configCtxDoc);

The resulting object should look something like this:

{
...
  "config": {
     ... stuff added by this->configCtx.getConfiguration(configCtxDoc)...
  }
...
}

I was hoping there'd be a way to create the sub document like so:

  JsonDocument doc;
  this->configCtx.getConfiguration(doc["config"]);

or:

  JsonDocument doc;
  this->configCtx.getConfiguration(doc.add<JsonObject>("config"));
bblanchon commented 3 months ago

Hello @briandilley,

You must use to<JsonObject>(), like so:

JsonDocument doc;
this->configCtx.getConfiguration(doc["config"].to<JsonObject>());

Best regards, Benoit

briandilley commented 3 months ago

@bblanchon that doesn't work:

    JsonDocument doc;
    doc["id"] = this->getId();
    doc["name"] = this->getName();
    doc["weight"] = this->getWeight();
    doc["demoable"] = this->isDemoable();

    this->configCtx.getConfiguration(doc["config"].as<JsonObject>());

Result:

src/LED_ShowManager.cpp:157:66: error: cannot bind non-const lvalue reference of type 'ArduinoJson::V703PB2::JsonObject&' to an rvalue of type 'ArduinoJson::V703PB2::detail::enable_if<true, ArduinoJson::V703PB2::JsonObject>::type' {aka 'ArduinoJson::V703PB2::JsonObject'}
bblanchon commented 3 months ago

cannot bind non-const lvalue reference of type JsonObject& to an rvalue of type JsonObject

Somewhere in your code, probably in the definition of getConfiguration(), there is a JsonObject& that must be replaced with JsonObject.

briandilley commented 3 months ago

Ok - why should it always be passed by value? Does that not create a copy? The goal here was to pass an object to this function to have the function alter it.

briandilley commented 3 months ago

This is the answer I was looking for

briandilley commented 3 months ago

Closing this