How to convert map to URL query string in Clojure/Compojure/Ring?

风流意气都作罢 提交于 2020-01-14 07:23:09

问题


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?


回答1:


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.




回答2:


Something like:

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

should do it...

REPL session:

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> 



回答3:


(defn to-query [inmap]
    (->> inmap
       (map (fn [[f s]] (str (name f) "=" (java.net.URLEncoder/encode (str s) "UTF-8"))))
       (clojure.string/join '&)
       ))

This code removes ':' from keywords, but will throw exception if keywords are numbers.

(to-query {:foo 1 :bar 2 :baz 3})
=> "foo=1&bar=2&baz=3"


来源:https://stackoverflow.com/questions/9745566/how-to-convert-map-to-url-query-string-in-clojure-compojure-ring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!