我知道我可以将查询字符串映射为keyworkd映射。
(defroutes my-routes
(GET "/" {params :query-params} params))但是,对于字符串键控映射,是否有同样的方法呢?(使用组合式或环型)
这里的重点不是迭代映射或使用函数,而是默认使用字符串键创建它。
{ :a "b" } -> {"a" "b"}发布于 2016-11-30 08:54:23
默认情况下,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下面创建查询字符串的哈希映射:
(defroutes handler
(wrap-params (GET "/" x
(prn-str (:params x)))))
$ curl localhost:3000/?a=55
{"a" "55"}此外,还可以使用ring.params.wrap-params:
(defroutes handler
(wrap-params (wrap-keyword-params (GET "/" x
(prn-str (:params x))))))
$ curl localhost:3000/?a=55
{:a "55"}发布于 2016-11-29 23:53:31
不确定构成,但您可以自己撤销它:
(use 'clojure.walk)
(stringify-keys {:a 1 :b {:c {:d 2}}})
;=> {"a" 1, "b" {"c" {"d" 2}}}https://stackoverflow.com/questions/40877192
复制相似问题