转换嵌套 clojure 数据结构的更好方法
A better way of transforming a nested clojure data structure
我有一个如下所示的 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 {})))
(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}}]}
我有一个如下所示的 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 {})))
(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}}]}