Skip to content

Commit 9bd09cf

Browse files
Add :vars to options to allow variables to be specified (#32)
* Add :vars to options to allow variables to be specified (#31) * Revise :vars to accept literal values, not JSON encoding of those values
1 parent 051d4bc commit 9bd09cf

File tree

2 files changed

+29
-10
lines changed

2 files changed

+29
-10
lines changed

Diff for: src/jq/api/api_impl.clj

+19-10
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@
1616

1717
(def jq-version Versions/JQ_1_6)
1818

19+
(defn ->JsonNode ^JsonNode [data]
20+
(if (instance? JsonNode data)
21+
data
22+
(.valueToTree mapper data)))
23+
1924
(defn ->absolute-path
2025
"FileSystemModuleLoader requires absolute paths."
2126
^Path [^String file-path]
@@ -50,16 +55,6 @@
5055
(.loadFunctions (BuiltinFunctionLoader/getInstance) jq-version scope)
5156
scope))
5257

53-
(defn new-scope
54-
(^Scope [] (Scope/newChildScope root-scope))
55-
(^Scope [opts]
56-
(let [^Scope scope (new-scope)
57-
module-paths (get opts :modules)
58-
module-paths (if (string? module-paths) [module-paths] module-paths)]
59-
(when (seq module-paths)
60-
(setup-modules! scope module-paths))
61-
scope)))
62-
6358
; Helper interface that specifies a method to get a string value.
6459
(definterface IContainer
6560
; net.thisptr.jackson.jq/Output
@@ -115,6 +110,20 @@
115110
^String [^JsonNode data ^JsonQuery query ^Scope scope ^IContainer output-container]
116111
(json-node->string (apply-json-query-on-json-node data query scope output-container)))
117112

113+
(defn new-scope
114+
(^Scope [] (Scope/newChildScope root-scope))
115+
(^Scope [opts]
116+
(let [^Scope scope (new-scope)
117+
module-paths (get opts :modules)
118+
module-paths (if (string? module-paths) [module-paths] module-paths)
119+
variables (get opts :vars)]
120+
(when (seq module-paths)
121+
(setup-modules! scope module-paths))
122+
(when variables
123+
(doseq [[key value] variables]
124+
(.setValue scope (name key) (->JsonNode value))))
125+
scope)))
126+
118127
(defn compile-query
119128
"Compiles a JQ query string into a JsonQuery object."
120129
^JsonQuery [^String query]

Diff for: test/jq/api_test.clj

+10
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,16 @@
99
(def query "map(.+1)")
1010
(def result-string "[2,3,4]")
1111

12+
(deftest variables
13+
(testing "passing variables in at compile time"
14+
(let [script "[$var1, $var2, $var3]"
15+
processor-fn (jq/flexible-processor script {:output :string
16+
:vars {:var1 "hello"
17+
"var2" "world"
18+
:var3 123}})
19+
resp (processor-fn "null")]
20+
(is (= resp "[\"hello\",\"world\",123]")))))
21+
1222
(deftest script-from-a-file
1323
(let [modules-dir "test/resources"
1424
script-file (str modules-dir "/scripts.jq")]

0 commit comments

Comments
 (0)