14

In Clojure / Compojure, how do I convert a map to a URL query string?

{:foo 1 :bar 2 :baz 3}

to

foo=1&bar=2&baz=3

Is there any utility method to do this in compojure?

4

3 回答 3

27

Yes, there is a utility for this already that doesn't involve Hiccup or rolling your own string/join/URLEncoder function:

user=> (ring.util.codec/form-encode {:foo 1 :bar 2 :baz 3})
"foo=1&bar=2&baz=3"
user=>

Compojure depends on ring/ring-core, which includes ring.util.codec, so you already have it.

于 2012-04-13T13:40:48.933 回答
8

就像是:

(defn params->query-string [m]
     (clojure.string/join "&" (for [[k v] m] (str (name k) "=" v))))

应该这样做...

REPL 会话:

user> (defn params->query-string [m]
         (clojure.string/join "&" 
            (for [[k v] m] 
               (str (name k) "="  (java.net.URLEncoder/encode v)))))
#'user/params->query-string
user> (params->query-string {:foo 1 :bar 2 :baz 3})
"foo=1&bar=2&baz=3"
user> 
于 2012-03-16T23:12:49.787 回答
0
(defn to-query [inmap]
    (->> inmap
       (map (fn [[f s]] (str (name f) "=" (java.net.URLEncoder/encode (str s) "UTF-8"))))
       (clojure.string/join '&)
       ))

此代码从关键字中删除 ':',但如果关键字是数字,则会引发异常。

(to-query {:foo 1 :bar 2 :baz 3})
=> "foo=1&bar=2&baz=3"
于 2019-05-14T20:06:23.993 回答