diff --git a/src/misc_json.c b/src/misc_json.c index b6eb18d1..9968a215 100644 --- a/src/misc_json.c +++ b/src/misc_json.c @@ -32,6 +32,29 @@ #include "logger.h" +json_object * +jparse_drilldown(json_object *haystack, const char *keys[]) +{ + json_object *needle; + json_bool found; + + while (*keys) + { + found = json_object_object_get_ex(haystack, *keys, &needle); + if (!found) + return NULL; + + if (json_object_get_type(needle) == json_type_array) + haystack = json_object_array_get_idx(needle, 0); + else + haystack = needle; + + keys++; + } + + return needle; +} + void jparse_free(json_object* haystack) { diff --git a/src/misc_json.h b/src/misc_json.h index 2a8410fe..05a5a880 100644 --- a/src/misc_json.h +++ b/src/misc_json.h @@ -33,6 +33,13 @@ #include #include +// Convenience macro so that instead of calling jparse with an array of keys +// to follow, you can call JPARSE_DRILLDOWN(haystack, "key1", "key2"...) +#define JPARSE_DRILLDOWN(haystack, ...) jparse_drilldown(haystack, (const char *[]){__VA_ARGS__, NULL}) + +json_object * +jparse_drilldown(json_object *haystack, const char *keys[]); + void jparse_free(json_object *haystack);