Search code examples
clojure

Transforming keys of a map in Clojure


I'm working with a REST API that represents an account with the following JSON:

{ "userName": "foo", "password": "bar", "emailId": "baz" }

I have a Clojure function to create an account that can be called like this:

(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. 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?


Solution

  • (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.