Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (ns some-namesace.blahblah
- (:require [clojure.test :refer :all]
- [some-other-namespace.blah.test-helper :refer [assert-equal]]
- [clojure.string :as str]))
- (defn- nesting-chain [expr] (re-seq #"[a-z]+|\[\]" expr))
- (defn transform
- [acc [chain v]]
- (if (= (last chain) "[]")
- (update-in acc (drop-last chain) concat [v])
- ; by default, concat nil [v] will create sequences
- ; if you really want vectors instead, replace the previous line by:
- ; (update-in acc (drop-last chain) (comp (partial into []) concat) [v])
- (assoc-in acc chain v)
- ))
- (defn parse-http-params
- [s]
- (->>
- (str/split s #"&")
- (map #(str/split % #"="))
- (map #(vector (nesting-chain (first %)) (second %)))
- (reduce transform {})))
- (deftest test-asserts
- (let [params-str "a[b][w][y]=3&a[c]=2&a[d][]=1&a[d][]=2&x[]=1&x[]=2&x[]=3"
- expected { "a" {"b" { "w" { "y" "3" } } "c" "2" "d" ["1" "2"] } "x" ["1" "2" "3"] }]
- (assert-equal expected (parse-http-params params-str))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement