[英]Transforming keys of a map in Clojure
I'm working with a REST API that represents an account with the following JSON:我正在使用 REST API 代表具有以下 JSON 的帐户:
{ "userName": "foo", "password": "bar", "emailId": "baz" }
I have a Clojure function to create an account that can be called like this:我有一个 Clojure function 来创建一个可以这样调用的帐户:
(create-account :username "foo" :password "bar" :email "baz")
What I want to do is map the nice keys that create-account
takes to the funky ones that the REST API expects.我想要做的是 map
create-account
需要的漂亮密钥到 REST API 期望的时髦密钥。 My current solution is this:我目前的解决方案是这样的:
(def clj->rest {:username :userName
:email :emailId})
(apply hash-map
(flatten (map
(fn [[k v]] [(or (clj->rest k) k) v])
args))) ;; args is the arguments to create-account, as above
Is there a more idiomatic way to accomplish this?有没有更惯用的方法来完成这个?
(clojure.set/rename-keys args clj->rest)
... mimics your solution, producing ... ...模仿您的解决方案,产生...
{:emailId "baz", :userName "foo", :password "bar"}
I take it you've worked out how to change this into the required JSON. 我认为您已经解决了如何将其更改为所需的JSON。
You may write a simple helper function to map all keys with given mapping function: 您可以编写一个简单的辅助函数,以使用给定的映射函数来映射所有键:
(defn kmap [f m]
(into {} (map #(update-in % [0] f) m)))
So, now you'll be able to easily map your arguments: 因此,现在您可以轻松映射参数:
(def clj->rest {:username :userName
:password :password
:email :emailId})
(kmap clj->rest args)
看起来不错,只需进行更改(apply hash-map (flatten ...
(into {} ...
以获得更多惯用的代码。
Since Clojure 1.11, you can use the update-keys function for key transforms, eg:从 Clojure 1.11 开始,可以使用update-keys function 进行密钥转换,例如:
(update-keys {"Content-Type" "text/plain"} str/lower-case)
=> {"content-type" "text/plain"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.