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.

CC BY-SA 4.0
1

1 Answer 1

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>());
        }
    }
}
CC BY-SA 4.0
1
  • 1
    That's perfect. It was the inner for loop I hadn't thought to try. Nice touch with the is<int>() test as well.
    – 8BitCoder
    Feb 7 at 19:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.