How to parse URL parameters in Clojure?

Viewed 10275

If I have the request "size=3&mean=1&sd=3&type=pdf&distr=normal" what's the idiomatic way of writing the function (defn request->map [request] ...) that takes this request and returns a map {:size 3, :mean 1, :sd 3, :type pdf, :distr normal}

Here is my attempt (using clojure.walk and clojure.string):

(defn request-to-map
   [request]
   (keywordize-keys
      (apply hash-map
             (split request #"(&|=)"))))

I am interested in how others would solve this problem.

7 Answers

Can also use this library for both clojure and clojurescript: https://github.com/cemerick/url

user=> (-> "a=1&b=2&c=3" cemerick.url/query->map clojure.walk/keywordize-keys)
{:a "1", :b "2", :c "3"}
Related