arduino-libraries / Arduino_JSON

Official JSON Library for Arduino
GNU Lesser General Public License v2.1
151 stars 60 forks source link

How to iterate over nested json? #63

Closed hitecSmartHome closed 4 months ago

hitecSmartHome commented 4 months ago

Hi! I have a json object which contains multiple objects

{
  "value1": "lala",
  "tests": {
     "testid":{
        "value1":"value1",
        "value2":"value2"
      },
      "testid2":{
        "value1":"value1",
        "value2":"value2"
      }
   }
}

How to iterate over "tests"?

This fails and crashes the esp

JSONVar JsonTests = test["tests"];
JSONVar keys = JsonTests.keys();
if( keys.length() != -1 ){
  for (int i = 0; i < keys.length(); i++) {
      JSONVar obj = JsonTests[keys[i]];
      // Get data obj["value1"];
  }
}
manchoz commented 4 months ago

Hi @hitecSmartHome, did you try the solution in https://github.com/arduino-libraries/Arduino_JSON/blob/master/examples/JSONValueExtractor/JSONValueExtractor.ino?

hitecSmartHome commented 4 months ago

I eventually solved it like this

if (test.hasOwnProperty("tests")) {
  // Get the top level object
  JSONVar JsonTests = test["tests"];
  // Get the keys of the object
  JSONVar keys = JsonTests.keys();
  if( keys.length() > 0 ){
    // Iterate over the keys
    for (int i = 0; i < keys.length(); i++) {
        // Get key as String
        String key = keys[i];
        // Get the object with the associated key
        JSONVar obj = JsonTests[key];
        // Get data obj["value1"];
    }
  }
}
hitecSmartHome commented 4 months ago

Would be much better if we had an iterator like this

for( JSONVar iterator : test["tests"] ){
   String key = iterator.key();
   JSONVar obj = iterator.value();
   // Get data like obj["value1"];
   String value = obj["value1"];
}

For loop would not run at all if hasOwnProperty() false. Much better syntax, less code. If we don't need the key we simply not call it.

JSONVar tests = test["tests"];
for( JSONVar iterator : tests ){
   JSONVar obj = iterator.value();
   String value = obj["value1"];
}