Skip to content

Commit 7cb423a

Browse files
committed
Support negative indexing
1 parent a82844c commit 7cb423a

File tree

3 files changed

+7
-2
lines changed

3 files changed

+7
-2
lines changed

src/json_path/walker.clj

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,11 @@
6565
(if (= "*" sel)
6666
(select-all (:current context))
6767
(if (sequential? obj)
68-
(let [index (Integer/parseInt sel)]
69-
(m/with-context index (nth obj index) (:current context)))
68+
(let [index (Integer/parseInt sel)
69+
effective-index (if (< index 0)
70+
(+ (count obj) index)
71+
index)]
72+
(m/with-context index (nth obj effective-index) (:current context)))
7073
(throw (Exception. "object must be an array.")))))
7174
(= :filter (first sel-expr)) (let [obj (:value (:current context))
7275
children (if (map? obj)

test/json_path/test/json_path_test.clj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
(at-path "$.foo[*]" {:foo ["a", "b", "c"]}) => ["a", "b", "c"]
1818
(at-path "$[*]" {:foo 1 :bar [2 3]}) => [1 [2 3]]
1919
(at-path "$..*" {:foo 1 :bar [2 3]}) => [1 [2 3] 2 3]
20+
(at-path "$[-2]" [1 2 3]) => 2
2021
(at-path "$.foo[?(@.bar=\"baz\")].hello"
2122
{:foo [{:bar "wrong" :hello "goodbye"}
2223
{:bar "baz" :hello "world"}]}) => ["world"]

test/json_path/test/walker_test.clj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343

4444
(facts
4545
(walk-selector [:index "1"] {:current (m/root ["foo", "bar", "baz"])}) => (m/create "bar" [1])
46+
(walk-selector [:index "-1"] {:current (m/root ["foo", "bar", "baz"])}) => (m/create "baz" [-1])
4647
(walk-selector [:index "*"] {:current (m/root [:a :b])}) => (list (m/create :a [0]) (m/create :b [1]))
4748
(walk-selector [:index "*"] {:current (m/root {:foo "bar"})}) => (list (m/create "bar" [:foo]))
4849
(walk-selector [:index "*"] {:current (m/root 1)}) => '()

0 commit comments

Comments
 (0)