3

I have a map like {:a "A" :b "B"} and want to convert its keys to strings, e.g. {"a" "A" "b" "B"}.

I have this function, which works:

(defn keyword-keys->strs [m]
  (zipmap
    (map name (keys m))
    (map second (vec m))))

But is there a more idiomatic or purpose-built way to do it?

Thanks!

3
  • (map second (vec m) -> (vals m) Commented Mar 11, 2019 at 9:26
  • 2
    simply (reduce-kv (fn [acc k v] (assoc acc (str k) v)) {} data) Commented Mar 11, 2019 at 10:36
  • @cfrick thanks for the tip, that was another one I had a hard time googling Commented Mar 11, 2019 at 14:47

1 Answer 1

11

There's a built-in function that will recursively convert map keys to strings:

(clojure.walk/stringify-keys {:a "A" :b "B"})
=> {"a" "A", "b" "B"}
(clojure.walk/stringify-keys {:a "A" :b {:c "C"}})
=> {"a" "A", "b" {"c" "C"}}
Sign up to request clarification or add additional context in comments.

2 Comments

ah, clojure.walk, of course! I should have looked there.
And don't forget the (more common) keywordize-keys: clojuredocs.org/clojure.walk/keywordize-keys

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.