Skip to content

Instantly share code, notes, and snippets.

@ivermac
Created September 7, 2018 03:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivermac/5d61ae7d1b6284b17a8ba36be87014ec to your computer and use it in GitHub Desktop.
Save ivermac/5d61ae7d1b6284b17a8ba36be87014ec to your computer and use it in GitHub Desktop.
Convert clojure hash-map to query param string
(defn get-query-params-str [query-params-map & [query-param-str]]
  "Converts a hash-map to a query param string containing the keys and values
   in the hash-map
   Note: this function assumes the values have already been url-encoded"
  (let [query-param-str (str query-param-str)
        query-param-str-blank? (string/blank? query-param-str)
        key (first (keys query-params-map))
        query-param-key (name (or key ""))
        query-param-val (and key (key query-params-map))]
    (case (count query-params-map)
      0 nil
      1 (string/join
          (if query-param-str-blank?
            ["?" query-param-key "=" query-param-val]
            [query-param-str "&" query-param-key "=" query-param-val]))
      (apply get-query-params-str
             (if query-param-str-blank?
                [query-params-map (str "?")]
                [(into {} (rest query-params-map))
                 (str query-param-str
                      (when-not (= query-param-str "?") "&")
                      query-param-key "=" query-param-val)])))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment