转换嵌套Clojure数据结构的更好方法

时间:2019-04-30 10:29:07

标签: dictionary clojure immutability zipper

我有一个Clojure地图,看起来像这样:

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

,我想将String键转换为keyword键。这是我想要的输出:

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

这是我用于此任务的代码:

(->> _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 {}))

是否有更好的方法? (可能涉及拉链?)

解决方案:

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

1 个答案:

答案 0 :(得分:2)

(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}}]}