From: Stephen Dolan Date: Fri, 19 Oct 2012 23:26:37 +0000 (+0100) Subject: Add a 'keys' function. Fixes #4. X-Git-Tag: jq-1.1~5 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=32e1b114df3067b000b26d11030fd265d2fee17a;p=jq Add a 'keys' function. Fixes #4. --- diff --git a/builtin.c b/builtin.c index c6ff785..c3d6af1 100644 --- a/builtin.c +++ b/builtin.c @@ -202,6 +202,39 @@ static void f_tostring(jv input[], jv output[]) { } } +static int string_cmp(const void* pa, const void* pb){ + const jv* a = pa; + const jv* b = pb; + int lena = jv_string_length(jv_copy(*a)); + int lenb = jv_string_length(jv_copy(*b)); + int minlen = lena < lenb ? lena : lenb; + int r = memcmp(jv_string_value(*a), jv_string_value(*b), minlen); + if (r == 0) r = lena - lenb; + return r; +} + +static void f_keys(jv input[], jv output[]) { + if (jv_get_kind(input[0]) == JV_KIND_OBJECT) { + int nkeys = jv_object_length(jv_copy(input[0])); + jv* keys = malloc(sizeof(jv) * nkeys); + int kidx = 0; + jv_object_foreach(i, input[0]) { + keys[kidx++] = jv_object_iter_key(input[0], i); + } + qsort(keys, nkeys, sizeof(jv), string_cmp); + output[0] = jv_array_sized(nkeys); + for (int i = 0; i