I know a global JsonObject shouldn't be used, but I have my reasons.

I have a JsonObject* functions and I want him to save the content of a file. With

functions=new JsonObject(jsonBuffer.as<JsonObject>());

I can access the JsonObject, but not when I leave the method. Can someone help me to understand why? (Don't give me a solution like: copy into a struct, I need a JsonObject ready to be read in all my code.

Full code:

JsonObject* functions;

void loadFunctions() {
  File file = SPIFFS.open("/functions.json", "r");
  if (!file) {
    Serial.println("Failed to open the file");
    size_t size = file.size();
    if (size > 512) {
      Serial.println("File size is too large");
      std::unique_ptr<char[]> buf(new char[size]);
      file.readBytes(buf.get(), size);
      DynamicJsonDocument jsonBuffer(256);
      DeserializationError error = deserializeJson(jsonBuffer, buf.get());
      if (error) {
        Serial.println("Failed to parse file ");
      } else {
        functions=new JsonObject(jsonBuffer.as<JsonObject>());
        Serial.println((*functions)["test"].as<String>()); //this doesn't work in another method
  • did you call loadFunctions anywhere? Sep 4 '19 at 13:28
  • Yes and the last Serial.println works, but not if I use it in another method (after this method)
    – Maray97
    Sep 4 '19 at 13:29

jsonBuffer is local to the function. When you leave the function the contents of jsonBuffer are lost.

functions just points to the internals of jsonBuffer to get its data (to save memory).

You can either:

  • Make the jsonBuffer global so it sticks around all the time, or
  • Have a secondary DynamicJsonDocument or StaticJsonDocument that is global to which you copy your objects once read from jsonBuffer.
  • Thank you, solved by using the second choice.
    – Maray97
    Sep 4 '19 at 13:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.