Skip to content

Instantly share code, notes, and snippets.

@ghadishayban
Last active December 25, 2015 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ghadishayban/6986030 to your computer and use it in GitHub Desktop.
Save ghadishayban/6986030 to your computer and use it in GitHub Desktop.
Destructure ugly JSON keys with underscores as symbols with dashes
(require '[clojure.string :as str])
(defn rename-underscore [sym]
[(symbol (str/replace (name sym) \_ \-))
(keyword sym)])
(defn udestructure [[lhs expr]]
(if (and (map? lhs)
(vector? (:_keys lhs)))
(let [msym (gensym)
bind-lhs (->> (:_keys lhs)
(map rename-underscore)
(into {}))]
[msym expr
bind-lhs msym
(dissoc lhs :_keys) msym])
[lhs expr]))
(defmacro letu [bindings & body]
(let [bents (partition 2 bindings)]
`(let [~@(mapcat udestructure bents)]
~@body)))
(comment
(letu [{a :a :_keys [ugly_name uglier_long_name]} {:ugly_name :foo
:uglier_long_name :bar
:a :baz}]
(= [ugly-name
uglier-long-name
a]
[:foo :bar :baz])))
;; true
@ghadishayban
Copy link
Author

complete with inscrutable symbol names in the macro

@ghadishayban
Copy link
Author

it might be a better API to specify :_keys [with-dashes] that way no underscore symbols are seen in the code, and there is congruity between binding symbols and the expr symbols...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment