akheron/jansson — Issue #45: Preprocessor macro for easy iteration of objects
Author: Coreh
Created: 2011-12-30 00:20:56+00:00
State: open

Hello @akheron,

First of all, I would like to thank you for taking the time to develop this library. It's incredibly well written and of immense value to a project I'm currently working on. The API is really consistent and pretty sane.

I would like to propose the addition of a new macro to the main header: `json_object_foreach`, with the purpose of reducing the amount of code required to iterate over an object. The macro definition would be something along the lines of:

#define json_object_foreach(k, v, x) \
const char *k; \
json_t *v; \
for(void *__json_iterator__ = json_object_iter(x); \
__json_iterator__ && \
(k = json_object_iter_key(__json_iterator__), v = json_object_iter_value(__json_iterator__), 1); \
__json_iterator__ = json_object_iter_next(x, __json_iterator__))

That allows the simplification of iteration code from:

const char *key;
json_t *value;
void *iter = json_object_iter(obj);
while(iter)
{
key = json_object_iter_key(iter);
value = json_object_iter_value(iter);
/* use key and value ... */
iter = json_object_iter_next(obj, iter);
}

To:

json_object_foreach(key, value, object)
{
/* use key and value ... */
}

I could not think of any drawbacks (performance of otherwise) of using this. If you like the idea, I can fork the repo and issue a pull request with the code.

Thanks.