Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 215
Sathish Avatar asked Mar 16 '12 22:03

Sathish


2 Answers

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.

like image 188
Lispnik Avatar answered Nov 17 '22 13:11

Lispnik


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> 
like image 28
sw1nn Avatar answered Nov 17 '22 13:11

sw1nn