1

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.

8BitCoder
  • 309
  • 1
  • 10

1 Answers1

0

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>());
        }
    }
}
001
  • 13,291
  • 5
  • 35
  • 66
  • 1
    That's perfect. It was the inner for loop I hadn't thought to try. Nice touch with the is() test as well. – 8BitCoder Feb 07 '22 at 19:30