3

I'm using SQLingvo and clojure.jdbc to access a PostgreSQL database.

Data is being returned as underscored maps, e.g. {:created_at "some date"}, when I expect hyphenated keywords like :created-at. Is there an easy way to marshall these maps back into their hyphenated versions?

Petrus Theron
  • 27,855
  • 36
  • 153
  • 287

2 Answers2

4

I've used clojure.walk/postwalk to accomplish this.

(defn transform-keys
  "Recursively transforms all map keys in coll with the transform-key fn."
  [transform-key coll]
  (letfn [(transform [x] (if (map? x)
                           (into {} (map (fn [[k v]] [(transform-key k) v]) x))
                           x))]
    (walk/postwalk transform coll)))

The first argument is a function that takes the existing key and returns the new one. In your case, you can convert the keyword to a string, replace the underscores with hyphens, and convert it back into a keyword.

https://gist.github.com/jeremyheiler/fe9256e540121e771285

Jeremy
  • 22,188
  • 4
  • 68
  • 81
1

It should be possible to provide {:identifiers #(.replace % \_ \-)} in options when you make a query, just as it is in clojure.java.jdbc.

Eugene Pakhomov
  • 9,309
  • 3
  • 27
  • 53