Getting the number of elements in an array

Hi,

I am decoding some JSON formated responses with this library and want to get the count of items within an array that is part of a response as the number of elements within the array changes. I have done a search for what to use and only found sizeof(json["Applications"]) which returns a constant value of 8.

Any help would be greatly appreciated :slight_smile:

Thanks,
Bay101

If you have a JsonArray object, just use array.size();

which returns a constant value of 8

That will be the number of bytes used by the array. The number of elements in the array depends on the data type. So, if you divide the number of bytes used by the array by the number of bytes in each element you will get the number of elements

byte numberOfElements = (sizeof(theArray) / sizeof(theArray[0]));
1 Like

bay101:
I am decoding some JSON formated responses with this library and want to get the count of items within an array

https://github.com/bblanchon/ArduinoJson/blob/master/include/ArduinoJson/JsonArray.hpp

Json array inherits public Internals::List<JsonVariant>, and so has all the methods that that class does.

https://github.com/bblanchon/ArduinoJson/blob/master/include/ArduinoJson/Data/List.hpp

That class has a method

 // Returns the numbers of elements in the list.
  // For a JsonObject, it would return the number of key-value pairs
size_t size() const;

And that's what you want.

JsonArray foo = whatever;
int numelements = foo.size();

Thankyou for all your responses :slight_smile:
Especially a massive thanks to PaulMurrayCbr, worked like a charm