Search code examples
esp32arduino-esp32arduinojson

Getting json keys from an array from an object using ArduinoJson


I'm having trouble getting the keys (and values) from "prefs" in the following json.

{
  "cmd": "set",
  "prefs": [
    {
      "coins": 4
    },
    {
      "enable": true
    }
  ]
}

Code to process json:

    DynamicJsonDocument doc(1024);
    deserializeJson(doc,"{\"cmd\":\"set\",\"prefs\":[{\"coins\":4},{\"enable\":true}]}");
    JsonObject root=doc.as<JsonObject>();
    for (JsonPair kv : root) {
        Serial.println(kv.key().c_str());
        Serial.println(kv.value().as<char*>());
    }
    JsonObject prefs=doc["prefs"];
    for (JsonPair kv : prefs) {
        Serial.println("here\n");
        Serial.println(kv.key().c_str());
//        Serial.println(kv.value().as<const char*>());
    }

I would expect to see the following output:

cmd
set
prefs
coins
enable

But I only get what seems to be an empty prefs object:

cmd
set
prefs

The example shown in the official docs almost gets me there, and is what I have in my code. This example from github is similar, but I can't seem to adapt it to my case.


Solution

  • Since prefs is an array, convert it to JsonArray

    JsonArray prefs = doc["prefs"].as<JsonArray>();
    for (JsonObject a : prefs) {
        for (JsonPair kv : a) {
            Serial.println(kv.key().c_str());
            if (kv.value().is<int>()) {
                Serial.println(kv.value().as<int>());
            }
            else {
                Serial.println(kv.value().as<bool>());
            }
        }
    }