bblanchon / ArduinoJson

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

[Question] Is there any simple approach to update a field on parsed object and print back? #553

Closed omersiar closed 7 years ago

omersiar commented 7 years ago

Hello, thanks for the great library, it really helped with my project. https://github.com/omersiar/esp-rfid

I have a json encoded configuration file on ESP8266 filesystem (SPIFFS) which I can quickly parse the information that i need like this:

bool loadConfiguration() {
  File configFile = SPIFFS.open("/auth/config.json", "r");
  if (!configFile) {
    Serial.println(F("[ WARN ] Failed to open config file"));
    return false;
  }
  size_t size = configFile.size();
  // Allocate a buffer to store contents of the file.
  std::unique_ptr<char[]> buf(new char[size]);
  // We don't use String here because ArduinoJson library requires the input
  // buffer to be mutable. If you don't use ArduinoJson, you may as well
  // use configFile.readString instead.
  configFile.readBytes(buf.get(), size);
  DynamicJsonBuffer jsonBuffer;
  JsonObject& json = jsonBuffer.parseObject(buf.get());
  if (!json.success()) {
    Serial.println(F("[ WARN ] Failed to parse config file"));
    return false;
  }
}

What I want to do is changing a field on parsed file for example "devicename":"esp-rfid" and write it back as a whole without breaking other fields.

Should I simply get the all the fields on memory, change the field that i want to change and create another buffer and create another JsonObject and print it to the file?

I'm already doing above, because i'm not aware of any other approach. Anyway, kind regards.

bblanchon commented 7 years ago

Hello @omersiar,

If you need to change a field in the JsonObject, you can modify it "in-place" and print back to file.

By the way, I'm not familiar with SPIFFS, butI believe you can pass the File object directly to parseObject().

Here is the scheme you could use:

File oldConfigFile, newConfigFile;
JsonObject& json = jsonBuffer.parseObject(configFile);
json["hello"] = "world";
json.printTo(newConfigFile);

See also:

Regards, Benoit

omersiar commented 7 years ago

Hello @bblanchon,

Thank you for the explanation. I can not believe this was that easy, thank you Sir, kind regards.

P.S. I will add this to wiki (bag of tricks maybe?), i searched everywhere for this.