Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Find out if element in JSON array is boolean, int, char, long, string, char[], String, ... #213

Closed
beegee-tokyo opened this issue Jan 31, 2016 · 2 comments
Labels
question v5 ArduinoJson 5

Comments

@beegee-tokyo
Copy link

Maybe a stupid question, but I cannot figure out from the API reference or the examples how to solve it.

I receive a JSON object with 2 JSON arrays:
{"msgkeys":["key1","key2","key3"],"msgs":["msg1",0.1234, 10]}
as jsonMsgs.

I can successfully parse the String to a JsonObject and to two JsonArrays with

// Convert message into JSON object
DynamicJsonBuffer jsonBuffer;
JsonObject& regJSON = jsonBuffer.parseObject(jsonMsgs);
if (regJSON.success()) {// Found some entries
   if (regJSON.containsKey("msgkeys")) {
      if (regJSON.containsKey("msgs")) {
         JsonArray& msgKeysJSON = regJSON["msgkeys"];
         JsonArray& msgsJSON = regJSON["msgs"];
         if (msgKeysJSON.size() == msgsJSON.size()) {
            for (int i=0; i<msgsJSON.size(); i++) {
               messageIDs[i] = msgKeysJSON.get<String>(i);
               // TODO get msgs and store in matching variable types
            }
         }
      }
   }
}

For the first array msgkeys, I know that all members are String, but for the second array msgs, the members can be anything allowed (boolean, float, double, signed char, .........) in a JSON array.

QUESTION:
How can I get the type of the entry for each member of the array msgsJSON????

I went down and up the API references and examples, but I could not find how to get information what type an entrance in the array is. I saw JsonVariant::is() in the API reference, but nothing how to use it or if it can be used on JsonArray.

@bblanchon
Copy link
Owner

bblanchon commented Jan 31, 2016

Please read FAQ: How to know the type of a value?.

Also, I strongly encourage you to use iterators to read all values from a array:

for (JsonArray::iterator it=array.begin(); it!=array.end(); ++it) {
   if (it->is<const char*>()) {
      Serial.print("It's a string");
   }
   if (it->is<int>()) {
      Serial.print("It's an int");
   }
}

@beegee-tokyo
Copy link
Author

Thanks for pointing me to the solution.

Repository owner locked and limited conversation to collaborators Sep 21, 2018
@bblanchon bblanchon added the v5 ArduinoJson 5 label Feb 6, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
question v5 ArduinoJson 5
Projects
None yet
Development

No branches or pull requests

2 participants