Skip to content

Commit

Permalink
Support negative indexing
Browse files Browse the repository at this point in the history
  • Loading branch information
cburgmer committed Jul 14, 2019
1 parent a82844c commit 7cb423a
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/json_path/walker.clj
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,11 @@
(if (= "*" sel)
(select-all (:current context))
(if (sequential? obj)
(let [index (Integer/parseInt sel)]
(m/with-context index (nth obj index) (:current context)))
(let [index (Integer/parseInt sel)
effective-index (if (< index 0)
(+ (count obj) index)
index)]
(m/with-context index (nth obj effective-index) (:current context)))
(throw (Exception. "object must be an array.")))))
(= :filter (first sel-expr)) (let [obj (:value (:current context))
children (if (map? obj)
Expand Down
1 change: 1 addition & 0 deletions test/json_path/test/json_path_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
(at-path "$.foo[*]" {:foo ["a", "b", "c"]}) => ["a", "b", "c"]
(at-path "$[*]" {:foo 1 :bar [2 3]}) => [1 [2 3]]
(at-path "$..*" {:foo 1 :bar [2 3]}) => [1 [2 3] 2 3]
(at-path "$[-2]" [1 2 3]) => 2
(at-path "$.foo[?(@.bar=\"baz\")].hello"
{:foo [{:bar "wrong" :hello "goodbye"}
{:bar "baz" :hello "world"}]}) => ["world"]
Expand Down
1 change: 1 addition & 0 deletions test/json_path/test/walker_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@

(facts
(walk-selector [:index "1"] {:current (m/root ["foo", "bar", "baz"])}) => (m/create "bar" [1])
(walk-selector [:index "-1"] {:current (m/root ["foo", "bar", "baz"])}) => (m/create "baz" [-1])
(walk-selector [:index "*"] {:current (m/root [:a :b])}) => (list (m/create :a [0]) (m/create :b [1]))
(walk-selector [:index "*"] {:current (m/root {:foo "bar"})}) => (list (m/create "bar" [:foo]))
(walk-selector [:index "*"] {:current (m/root 1)}) => '()
Expand Down

0 comments on commit 7cb423a

Please sign in to comment.