A better way of transforming a nested clojure data structure

73 Views Asked by At

I have a clojure map that looks like this:

{"l1" [{"name" "s1", "url" "something", "coordinates" {"latitude" 100, "longitude" 200}}
       {"name" "s2", "url" "something", "coordinates" {"latitude" 150, "longitude" 77.08472222222221}}]}

and I want to convert the String keys into keyword keys. This is the output I want:

{"l1" ({:name "s1", :url "something", :coordinates {:latitude 100, :longitude 200}}
       {:name "s2", :url "something", :coordinates {:latitude 150, :longitude 77.08472222222221}})}

This is the code I used for this task:

(->> _tt
     (map (fn [[k v]]
            [k (map (fn [entry]
                      (->> entry
                           (map (fn [[k v]]
                                  [(keyword k) (if (= k "coordinates")
                                                 (->> v
                                                      (map (fn [[k v]]
                                                             [(keyword k) v]))
                                                      (into {}))
                                                 v)]))
                           (into {})))
                    v)]))
     (into {}))

Is there a better way of doing this? (possibly involving zippers?)

Solution:

(->> _tt
     (map (fn [[k v]]
            [k (clojure.walk/keywordize-keys v)]))
     (into {})))
1

There are 1 best solutions below

1
akond On BEST ANSWER
(let [a {"l1" [{"name" "s1", "url" "something", "coordinates" {"latitude" 100, "longitude" 200}}
               {"name" "s2", "url" "something", "coordinates" {"latitude" 150, "longitude" 77.08472222222221}}]}
      ]
    (clojure.walk/keywordize-keys a))
=>
{:l1 [{:name "s1", :url "something", :coordinates {:latitude 100, :longitude 200}}
      {:name "s2", :url "something", :coordinates {:latitude 150, :longitude 77.08472222222221}}]}