[misc] Add json_drilldown() function

Will descend into a json object along the path set by a list of keys
This commit is contained in:
ejurgensen 2020-02-11 14:13:18 +01:00
parent d86ca1176d
commit 937f4431f8
2 changed files with 30 additions and 0 deletions

View File

@ -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)
{

View File

@ -33,6 +33,13 @@
#include <stddef.h>
#include <time.h>
// 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);