]> granicus.if.org Git - jq/commitdiff
Add support for negative indices for .[]; fix #462
authorWilliam Langford <wlangfor@gmail.com>
Fri, 4 Jul 2014 16:08:47 +0000 (12:08 -0400)
committerNicolas Williams <nico@cryptonector.com>
Sun, 6 Jul 2014 06:40:22 +0000 (01:40 -0500)
Signed-off-by: Nicolas Williams <nico@cryptonector.com>
docs/content/3.manual/manual.yml
jv_aux.c
tests/all.test

index 973e8d855c7e4dd6caaa4a847f5dcc7739fc29b6..ac0e70e0956308cc3f02a1d0464897623f6beddd 100644 (file)
@@ -256,6 +256,11 @@ sections:
           the array), or omitted (in which case it refers to the start
           or end of the array).
 
+          The `.[2]` syntax can be used to return the element at the
+          given index.  Negative indices are allowed, with -1 referring
+          to the last element, -2 referring to the next to last element,
+          and so on.
+
           The `?` "operator" can also be used with the slice operator,
           as in `.[10:15]?`, which outputs values where the inputs are
           slice-able.
@@ -285,6 +290,10 @@ sections:
             input: '["a","b","c","d","e"]'
             output: ['["d", "e"]']
 
+          - program: '.[-2]'
+            input: '[1,2,3]'
+            output: ['2']
+
       - title: "`.[]`"
         body: |
 
index 5f233e054601077f7d9c19a66d42855545cecb05..dec5ce20d01d5ea16c90a24acb2cbd4462baa2ea 100644 (file)
--- a/jv_aux.c
+++ b/jv_aux.c
@@ -57,7 +57,10 @@ jv jv_get(jv t, jv k) {
     }
   } else if (jv_get_kind(t) == JV_KIND_ARRAY && jv_get_kind(k) == JV_KIND_NUMBER) {
     if(jv_is_integer(k)){
-      v = jv_array_get(t, (int)jv_number_value(k));
+      int idx = (int)jv_number_value(k);
+      if (idx < 0)
+        idx += jv_array_length(jv_copy(t));
+      v = jv_array_get(t, idx);
       if (!jv_is_valid(v)) {
         jv_free(v);
         v = jv_null();
index 4bd15cee586f4035c34bf70513fcea9c02f4b8c1..1fdb10a02178132a8ea2c7281080fb6da234bfd4 100644 (file)
@@ -202,6 +202,10 @@ null
 2
 3
 
+.[-2]
+[1,2,3]
+2
+
 [range(0;10)]
 null
 [0,1,2,3,4,5,6,7,8,9]