我知道我可以将查询字符串映射为keyworkd地图。
(defroutes my-routes
(GET "/" {params :query-params} params))
但有没有办法用字符串键控地图做同样的事情? (使用Compojure或Ring )
这里的要点不是迭代地图或使用函数,但默认情况下使用字符串键创建。
{ :a "b" } -> {"a" "b"}
答案 0 :(得分:1)
Compojure 1.5.1默认不解析任何查询字符串(不使用任何中间件)。但是,在早期版本中可能会有所不同。
(require '[compojure.core :refer :all])
(require '[clojure.pprint :refer [pprint]])
(defroutes handler
(GET "/" x
(with-out-str (pprint x)))) ;; just a way to receive a pretty printed string response
$ curl localhost:3000/?a=b
{:ssl-client-cert nil,
:protocol "HTTP/1.1",
:remote-addr "127.0.0.1",
:params {}, ;; EMPTY!
:route-params {},
:headers
{"user-agent" "curl/7.47.1", "accept" "*/*", "host" "localhost:3000"},
:server-port 3000,
:content-length nil,
:compojure/route [:get "/"],
:content-type nil,
:character-encoding nil,
:uri "/",
:server-name "localhost",
:query-string "a=b", ;; UNPARSED QUERY STRING
:body
#object[org.eclipse.jetty.server.HttpInputOverHTTP 0x6756d3a3 "HttpInputOverHTTP@6756d3a3"],
:scheme :http,
:request-method :get}
Ring提供ring.params.wrap-params
中间件,它解析查询字符串并在params-key下创建它的hashmap:
(defroutes handler
(wrap-params (GET "/" x
(prn-str (:params x)))))
$ curl localhost:3000/?a=55
{"a" "55"}
可以使用Additionaly ring.params.wrap-params
:
(defroutes handler
(wrap-params (wrap-keyword-params (GET "/" x
(prn-str (:params x))))))
$ curl localhost:3000/?a=55
{:a "55"}
答案 1 :(得分:0)
不确定compojure,但您可以自行撤消:
(use 'clojure.walk)
(stringify-keys {:a 1 :b {:c {:d 2}}})
;=> {"a" 1, "b" {"c" {"d" 2}}}