I'm using a json file in the data folder. I want to use this as a config file and update it with values as needed. I have a simple sketch to store ssid and password. First read it out, then change it, then read it out again via the serial monitor for testing.
The problem is the first read seems to already have been overwritten, even if i call the overwrite function much later, I have tested this with different delays between the first read and the overwrite function.
It seems pretty straight forward to do, so why does it show the overwritten value before the function is called?
Here is the code:
readJSON(LITTLEFS, "/config.json");
String test = config["ssid"];
Serial.println(test);
delay(10);
String test2;
config["ssid"] = "InternetName";
serializeJson(config, test2);
writeFile(LITTLEFS, "/config.json", test2.c_str()); // String to Const char*
delay(10);
readJSON(LITTLEFS, "/config.json");
String test3 = config["ssid"];
Serial.println(test3);
Here are readJSON and writeFile functions:
DynamicJsonDocument config(1024);
void readJSON(fs::FS &fs, const char * path){
Serial.printf("Reading Json: %s\r\n", path);
String output;
File file = fs.open(path);
if(!file || file.isDirectory()){
Serial.println("- failed to open file for reading");
return;
}
Serial.println("- read from file:");
while(file.available()){
//Serial.write(file.read());
char intRead = file.read();
output += intRead;
}
deserializeJson(config, output);
file.close();
}
void writeFile(fs::FS &fs, const char * path, const char * message){
Serial.printf("Writing file: %s\r\n", path);
File file = fs.open(path, FILE_WRITE);
if(!file){
Serial.println("- failed to open file for writing");
return;
}
if(file.print(message)){
Serial.println("- file written");
} else {
Serial.println("- write failed");
}
file.close();
}
config.json:
{
"ssid": "nameofinternet",
"password": "password"
}
Output:
Reading Json: /config.json
- read from file:
InternetName
Writing file: /config.json
- file written
Reading Json: /config.json
- read from file:
InternetName