1

My mongodb schema has a JSON hierarchy to it. When I get the field params from compojure, the hash is in flat dotted notation like {"a.b" 1, "a.c" 2, "d.e" 3}. I'm wanting to use monger to insert the data, but that expects a real hierarchical format like {:a {:b 1, :c 2}, :d {:e 3}}. Is there any way to automatically convert from one to the other?

lobsterism
  • 3,469
  • 2
  • 22
  • 36

1 Answers1

3

Nothing automatic that I know of, but it's pretty straightforward to do the conversion manually:

=> (require 'clojure.string)
=> (defn nest-keys [x]
     (reduce (fn [m [k v]]
               (assoc-in m (map keyword (clojure.string/split k #"\.")) v))
             {}
             x))
=> (nest-keys {"a.b" 1 "a.c" 2 "d.e" 3})
{:d {:e 3}, :a {:c 2, :b 1}}
Alex
  • 13,811
  • 1
  • 37
  • 50
  • Really great! Any chance you can come up with an equally succinct reverse conversion? – lobsterism Jun 17 '13 at 18:49
  • Logic for the reverse is a bit trickier but here's what I came up with: https://gist.github.com/alexhall/5799651 – Alex Jun 17 '13 at 19:39