akheron / jansson

C library for encoding, decoding and manipulating JSON data
http://www.digip.org/jansson/
Other
3.05k stars 811 forks source link

new method json_object_get_nested #541

Closed fish9370 closed 4 years ago

fish9370 commented 4 years ago

Hello, can you add new method for nested query?

using: json_t *expires = json_object_get_nested(conf, "sip expires")

it's return NULL if not found

json_t *json_object_get_nested(const json_t *json, const char *keys) {
    char *str = strdup(keys);
    char delim[] = " ";
    char *saveptr;
    char *ptr = strtok_r(str, delim, &saveptr);
    const json_t *root = json;
    json_t *res = NULL;

    while (ptr != NULL) {
        if (!(res = json_object_get(root, ptr)))
            break;

        root = res;
        ptr = strtok_r(NULL, delim, &saveptr);
    }

    free(str);
    return res;
}
ploxiln commented 4 years ago

There exists a featureful standard for the syntax of the "keys" argument in your example, called json-path: https://goessner.net/articles/JsonPath/ ... but that is quite a lot of functionality, which probably will not be implemented in jansson any time soon.

However, jansson already has a different function which can give you convenient nested access, json_unpack()

json_t *res = NULL;
int err = json_unpack(json, "{s:{s:o}}", "sip", "expires", &res);
// check err, then use res