Search code examples
esp8266spiffsarduinojson

How to read json file from ESP8266's SPIFFS with ArduinoJSON 6?


I am currently working on a project with ESP8266 (ESP-12E) and I need to store information in a json file (more convenient to access via the web interface and easier to manage than EEPROM for me).

My problem is the following: I'm using the latest version of ArduinoJSON (6), but I haven't seen many examples except on their site, and this code doesn't work for me :

void DeleteCycle(size_t idtodelete) {
  File schedules = SPIFFS.open("/schedules.json", "r");

  if(schedules && schedules.size()) {

    DynamicJsonDocument schedulesjson(1300);
    DeserializationError err = deserializeJson(schedulesjson, schedules);
    Serial.println(err.c_str());
      if (err) {
        Serial.print(F("deserializeJson() failed with code "));
        Serial.println(err.c_str());
      }
      else {

        JsonArray array = schedulesjson.to<JsonArray>();
        // array.remove(0);
        serializeJson(array, Serial);

      }

      schedules.close();
  }
  else {
    Serial.println("Failed to read file.");
  }

}

I guess the problem is the JsonArray, it's empty ! But my JsonDocument is not, because if I do

JsonObject obj = schedulesjson[0];
String test = obj["name"];
Serial.println("Test : " + test);

I get the first key value (name) of my array at index 0

This is my first post on StackOverflow, I hope I did it right, thanks in advance for your help!


Solution

  • I answer myself because I found the solution to my problem: writing

    schedulesjson.to<JsonArray>();
    

    empties the json document, so you have to put it before

    DeserializationError err = deserializeJson(schedulesjson, schedules);