Clojure: Convert hash-maps key strings to keywords?
You can also use the clojure.walk
library to achieve the desired result with the function keywordize-keys
(use 'clojure.walk)
(keywordize-keys {"name" "Tylenol", "how" "instructions"})
;=> {:name "Tylenol", :how "instructions"}
This will walk the map recursively as well so it will "keywordize" keys in nested map too
http://clojuredocs.org/clojure_core/clojure.walk/keywordize-keys
There is a handy function called keyword that converts Strings into the appropriate keywords:
(keyword "foo")
=> :foo
So it's just a case of transforming all the keys in your map using this function.
I'd probably use a list comprehension with destructuring to do this, something like:
(into {}
(for [[k v] my-map]
[(keyword k) v]))
I agree with djhworld, clojure.walk/keywordize-keys
is what you want.
It's worth peeking at the source code of clojure.walk/keywordize-keys
:
(defn keywordize-keys
"Recursively transforms all map keys from strings to keywords."
[m]
(let [f (fn [[k v]] (if (string? k) [(keyword k) v] [k v]))]
(clojure.walk/postwalk (fn [x] (if (map? x) (into {} (map f x)) x)) m)))
The inverse transform is sometimes handy for java interop:
(defn stringify-keys
"Recursively transforms all map keys from keywords to strings."
[m]
(let [f (fn [[k v]] (if (keyword? k) [(name k) v] [k v]))]
(clojure.walk/postwalk (fn [x] (if (map? x) (into {} (map f x)) x)) m)))